Can't call Auth::user() on controller's constructor

后端 未结 3 1447
情书的邮戳
情书的邮戳 2020-11-28 13:49

I\'m trying to check if the user has permission to a certain model. Up until now (with Laravel 5.2), I added this code at the constructor:

public function __         


        
3条回答
  •  鱼传尺愫
    2020-11-28 14:20

    See here:

    Session In The Constructor

    In previous versions of Laravel, you could access session variables or the authenticated user in your controller's constructor. This was never intended to be an explicit feature of the framework. In Laravel 5.3, 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:

    middleware(function ($request, $next) {
                $this->projects = Auth::user()->projects;
    
                return $next($request);
            });
        }
    }
    

    Of course, you may also access the request session data or authenticated user by type-hinting the Illuminate\Http\Request class on your controller action:

    /**
     * Show all of the projects for the current user.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return Response
     */
    public function index(Request $request)
    {
        $projects = $request->user()->projects;
    
        $value = $request->session()->get('key');
    
        //
    }
    

提交回复
热议问题