Auth::user() returns null

后端 未结 6 1498
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-03 04:47

I use Laravel 5.2 and have a problem with middleware. There is the code in the routes.php


    use Illuminate\\Contracts\\Auth\\Access\\Gate;


    Route::group([         


        
6条回答
  •  暖寄归人
    2020-12-03 05:14

    I faced a situation where Auth::user() always returns null, it was because I was trying to get the User in a controller's constructor.

    I realized that you can't access the authenticated user in your controller's constructor because the middleware has not run yet.

    As an alternative, you can define a Closure based middleware directly in your controller's constructor.

    namespace App\Http\Controllers;
    
    use App\User;
    use Illuminate\Support\Facades\Auth;
    use App\Http\Controllers\Controller;
    
    class ProjectController extends Controller
    {
        protected $user;
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware(function ($request, $next) {
    
                $this->user = Auth::user();
    
                return $next($request);
            });
        }
    }
    

提交回复
热议问题