Laravel 5.3 auth check in constructor returning false

前端 未结 3 660
Happy的楠姐
Happy的楠姐 2020-11-27 21:07

I\'m using Laravel 5.3 and I\'m trying to get the authenticated user\'s id in the constructor method so I can filter

相关标签:
3条回答
  • 2020-11-27 21:36

    docs

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

    As an alternative, you may define a Closure based middleware directly in your controller's constructor. Before using this feature, make sure that your application is running Laravel 5.3.4 or above:

    class ProjectController extends Controller
    {
        /**
         * All of the current user's projects.
         */
        protected $projects;
    
        /**
         * Create a new controller instance.
         *
         * @return void
         */
        public function __construct()
        {
            $this->middleware(function ($request, $next) {
                $this->projects = Auth::user()->projects;
    
                return $next($request);
            });
        }
    }
    
    0 讨论(0)
  • 2020-11-27 21:39

    It fails because you call $this->middleware('auth'); after parent::__construct();. It means that you auth middleware is not loaded properly.

    0 讨论(0)
  • 2020-11-27 21:45

    Since 5.3 Auth::check will not work in a controller's construtor, it's one of undocumented changes. So, you need to move it to middleware or do check in controller methods instead or move project to 5.2.x.

    0 讨论(0)
提交回复
热议问题