Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5.6 Access auth()->user() in controller constructor?

I am trying to access auth()->user() in controller constructor, but it always return null.

I have tried below, but no luck!

protected $user;

function __construct() {
    $this->middleware(function ($request, $next) {
        $this->user = auth()->user();

        return $next($request);
    }); 

}

Is there any way to do this?

--Thanks

like image 533
Kaleem Avatar asked Jul 24 '18 10:07

Kaleem


1 Answers

Controller Constructor is called before Middlewares. So you can not get User information inside Constructor().

My advice is create private function that sets User, and call this inside your functions.

like image 144
Ts8060 Avatar answered Nov 08 '22 20:11

Ts8060