Reputation: 499
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
Upvotes: 7
Views: 4269
Reputation: 1
Thanks to @Ts8060 i had the idea to create a singleton for doing that.
/** @var User */
private static $user;
/**
* Singleton
*
* @return User
*/
public function getUser() {
if(empty(static::$user)) {
static::$user = Auth::user();
}
return static::$user;
}
Upvotes: 0
Reputation: 1070
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.
Upvotes: 4
Reputation: 1732
I think that auth middleware run after create controller, you may do somethink like this in your controller
public function callAction($method, $parameters)
{
$this->middleware(function ($request, $next) {
$this->user = auth()->user();
return $next($request);
});
return parent::callAction($method, $parameters);
}
Upvotes: -2