Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 923
Chris Avatar asked May 09 '15 03:05

Chris


2 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

like image 140
TomLingham Avatar answered Nov 01 '22 10:11

TomLingham


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.

like image 29
hayatbiralem Avatar answered Nov 01 '22 09:11

hayatbiralem