Laravel, Auth::user() in controller

后端 未结 9 1789
说谎
说谎 2021-02-20 11:44

Laravel framework- Why aren\'t I able to use Auth::user(), (to see if user has been logged in) in the controller of the laravel project. Is the Session not connected to the cont

相关标签:
9条回答
  • 2021-02-20 12:01

    in your controllers constructor:

    public function __construct(){
        $this->middleware('auth');
    }
    
    0 讨论(0)
  • 2021-02-20 12:02

    If you're on Laravel 5.x, you'll probably have the auth middleware component. That might be the missing link.

    I often use a pattern like this in my controllers:

    public function __construct()
        {
            $this->middleware('auth');
            $this->user =  \Auth::user();
        }
    

    then you can

    if ($this->user .. )

    or

    if ($this->user->can('something')) with Entrust or similar

    0 讨论(0)
  • 2021-02-20 12:03

    You need to use the Auth facade in the controller;

    add this line just before class definition.

    use Auth;
    0 讨论(0)
  • 2021-02-20 12:09

    Use Auth::check()function to check if user is logged or not

    0 讨论(0)
  • 2021-02-20 12:10

    The problem is that you haven't included the Auth facade.

    In your HomeController.php do:

    use Illuminate\Support\Facades\Auth;
    
    0 讨论(0)
  • 2021-02-20 12:10

    I have the same problem. The solution I've found, is to not use \Auth::user() (it returns null). Instead, go through the guard like this: \Auth::guard('mrm')->User(). Obviously replace 'mrm' with whatever auth guard you are using.

    This works, correctly returning the current user even when Auth::User returns null, and you can also use other methods on it - e.g. \Auth::guard('mrm')->check() instead of \Auth::check() (which always returns false).

    No idea why the Auth facade doesn't work, but at least there is an alternative that does.

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