What is the best way to declare a variable to be used in all the methods within my controllers and my models:
example .. I want to replace: Auth::user() by: $this->user
What would be the best way to do it?
What is the best way to declare a variable to be used in all the methods within my controllers and my models:
example .. I want to replace: Auth::user() by: $this->user
What would be the best way to do it?
For Laravel 5.3.4+
Declare the property in your controller and then you can do it like this in its __construct
method:
protected $user;
public function __construct()
{
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
return $next($request);
});
}
For versions below, you can just $this->user = Auth::user();
inside __construct
.
Reference: https://laravel.com/docs/5.3/upgrade#5.3-session-in-constructors
If you attempt to set a user in your Controller.php
's __construct
method you will find it won't work.
This won't work:
public function __construct()
{
$this->user = auth()->check() ? auth()->user() : null;
}
This is by design, according Taylor, the framework's creator. He discourages setting your user in the base controller - but, it's up to you how you want to do things. There is a way around this. If you wanted $this->user
to be accessible in every controller, you would add this to your Controller.php
file:
protected function setUser()
{
$this->user = auth()->check() ? auth()->user() : null;
}
Then in your __construct
method call it:
public function __construct()
{
$this->setUser();
}
Now, you can access this->user
from any controller method. It will be null
if not set, but if you are using Laravel's standard auth guard you shouldn't have much of a problem with unauthenticated users getting through.