Laravel 5.2 包:Auth 方法在控制器的构造函数中失败

Laravel 5.2 Package : Auth methods fail in constructor of controller

我已经为我的包添加了一个控制器,我需要在这个控制器的构造函数中调用 Auth 方法,但我收到以下错误:

ReflectionException in Container.php line 734: Class hash does not exist

这是我的代码:

use Auth;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Session;

class CartController extends Controller
{
    private $customer;

    public function __construct()
    {
         $this->middleware('auth', ['except' => ['add']]);
         $multiauth = config('cart.multiauth');
         if ($multiauth) {
             $guard       = config('auth.defaults.guard');
             $this->customer = Auth::guard($guard)->user();
         } else {
             $this->customer = Auth::user();
         }
    }

    public function add()
    {
        // Code
    }
}

当我在其他函数中添加构造函数代码时,它可以正常工作,但是当从控制器的构造函数中调用它时,它会失败。

我已经搜索了很多,但没有找到可行的解决方案。

你不能在控制器中使用中间件 __construct ,创建一个函数并使用它

我已经通过添加一个中间件解决了这个问题:

namespace myNamespace\myPackage;

use Closure;
use Illuminate\Support\Facades\Auth;

class CustomerMiddleware
{
     public function handle($request, Closure $next)
     {
         $multiauth = config('cart.multiauth');
         if ($multiauth) {
             $guard   = config('auth.defaults.guard');
             $customer = Auth::guard($guard)->user();
         } else {
             $customer = Auth::user();
         }

         $request->attributes->add(['customer' => $customer]);

         return $next($request);
     }
}

然后我将这个中间件用于 'cart/add' 路由:

Route::group(['middleware' => ['web']], function () {
    Route::group(['middleware' => 'customer'], function() {
        Route::post('cart/add',
                    'myNamespace\myPackage\CartController@add');
    });
});

因此,通过检查 'CartController' 的 'add' 方法中的 $request->get('customer') 参数,我可以访问当前用户的信息:

class CartController extends Controller
{
    public function __construct() { }

    public function add()
    {
       $customer = $request->get('customer');
       // Code 
    }
}

我希望这对其他人有帮助:)