简体   繁体   中英

Laravel 5.2 Package : Auth methods fail in constructor of controller

I have added a controller for my package and I need to call Auth methods inside the constructor of this controller but I get the following error :

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

Here is my code :

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
    }
}

When I add the code of constructor inside the other functions it works properly but it fails when it is called from constructor of the controller.

I have searched alot for this and found no working solution.

I've solved the problem by adding a middleware :

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);
     }
}

Then I used this middleware for the 'cart/add' route :

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

So by checking the $request->get('customer') parameter inside the 'add' method of 'CartController', I have access to information of current user :

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

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

I hope this helps someone else :)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM