1

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?

php_boy
  • 41
  • 7
  • I definitely don't suggest doing this. It adds unnecessary logic - especially considering you can use the super globals – Derek Pollard Jul 09 '18 at 22:40
  • please can u help me in another question https://stackoverflow.com/questions/51249476/laravel-5-5-validation-message – php_boy Jul 09 '18 at 22:45

2 Answers2

2

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

Wreigh
  • 3,215
  • 16
  • 37
1

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.

Mark
  • 1,255
  • 1
  • 13
  • 25