Taylor Swift Taylor Swift - 3 months ago 86
PHP Question

Laravel 5.3 - Sharing $user variable to all views

So after finding out that sharing views in Controller.php's constructer no longer works because it always returns

, I am looking for a different way to do it.

I am simply looking for a way to pass a
variable with the current signed in user to all my views.

Previous way which worked in 5.2 and below:

public function __construct()
view()->share('signed_in', Auth::check());
view()->share('user', Auth::user());

This no longer works. How else can I share variables?

I have tried:

public function __construct()
$this->middleware(function ($request, $next) {
$this->user = Auth::user();
$this->signed_in = Auth::guest();

view()->share('signed_in', $this->signed_in);
view()->share('user', $this->user);

return $next($request);

But the code above does not work. It does load the page without a "Undefined Variable $user" error but it just show the navigation bar and then nothing else. It also messes up the site CSS for some reason.

Is there any other way I can do it?
Please help. Thank you.


Using the middleware callback the way you do is a correct way to go about this, but your assignment is wrong.

Use this instead:

$this->signed_in = Auth::check();