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:
Note the guard->user variable is populated, but the user variable is null.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With