Home » Php » How to share Auth::user among all views in Laravel 5?

How to share Auth::user among all views in Laravel 5?

Posted by: admin November 30, 2017 Leave a comment

Questions:

I need to share the currently logged in user to all views. I am attempting to use the view->share() method within AppServiceProvider.php file.

I have the following:

<?php namespace App\Providers;

use Illuminate\Support\ServiceProvider;

use Illuminate\Contracts\Auth\Guard;


class AppServiceProvider extends ServiceProvider {


    public function boot(Guard $guard)
    {
        view()->share('guard', $guard);
        view()->share('user', $guard->user());
    }

    //..
}

However, when I hit up a view (after logging in), the user variable is null. Strangely, the $guard->user (the protected attribute, not the public method user()) is not. The output I get is the following:

enter image description here

Note the guard->user variable is populated, but the user variable is null.

Answers:

Better off using View Composers for this one.

In your ComposerServiceProvider in boot():

view()->composer('*', 'App\Http\ViewComposers\GlobalComposer');

In HTTP/ViewComposers create a class GlobalComposer, and create the function:

public function compose( View $view )
{
    $view->with('authUser', Auth::user());
}

http://laravel.com/docs/5.0/views#view-composers

Questions:
Answers:

You can solve this problem without creating a file.

Add these codes to boot() action of your ServiceProvider and that’s it.

view()->composer('*', function($view){
  $view->with('user', Auth::user());
});

Source also same: http://laravel.com/docs/5.0/views#view-composers

Look Wildcard View Composers.