Laravel ships with two authentication controllers out of the box, which are located in the
App\Http\Controllers\Auth
namespace....
You may access the authenticated user via the Auth facade:
$user = Auth::user();
Reference: Laravel 5.2 Documentation
I'm able to log in successfully and I'm redirected to the correct place as defined in the AuthController.php
, but now I need access to the $user
object in most of my views such as for checking the user's information, access priveleges, etc.
How do I properly provide access to the $user
variable on all of my views?
User imJohnBen of Laracast asked how a Laravel 5 service provider can be used to share view variables. He later shares how he was able to use the existing ComposerServiceProvider
and added a GlobalComposer
to be able to share variables on all the views.
I followed his answer but there was a missing step. I couldn't contribute to the Laracast forums, thus leading to the creation of this StackOverflow question.
The Laravel version I'm using here is Laravel 5.2.*
.
Find the existing ComposerServiceProvider
class. I found mine in vendor/laravel/framework/src/Illuminate/Foundation/Providers/ComposerServiceProvider.php
.
Import/reference the ViewFactory
dependency at the top of the file.
use Illuminate\Contracts\View\Factory as ViewFactory;
Add the boot
method, or modify it if it exists already. Make sure the ViewFactory
was injected (add it as a parameter in the boot function):
/**
* Register bindings in the container.
*
* @return void
*/
public function boot(ViewFactory $view)
{
$view->composer('*', 'App\Http\ViewComposers\GlobalComposer');
}
ViewComposers
folder in your app/Http
folder.Make a GlobalComposer.php
file in the ViewComposers
folder, containing the following:
<?php
namespace App\Http\ViewComposers;
use Illuminate\Contracts\View\View;
use Illuminate\Support\Facades\Auth;
class GlobalComposer {
/**
* Bind data to the view.
*
* @param View $view
* @return void
*/
public function compose(View $view)
{
$view->with('user', Auth::user());
}
}
(The missing step) Finally, make sure everything is wired up by going to your config/app.php
file and making sure that ComposerServiceProvider
is in your providers list.
'providers' = [
/*
* Laravel Framework Service Providers...
*/
Illuminate\Auth\AuthServiceProvider::class,
Illuminate\Broadcasting\BroadcastServiceProvider::class,
// etc...
Illuminate\Foundation\Providers\ComposerServiceProvider::class,
]
Afterwards, the $user
variable and any other variables you define in the GlobalComposer
will be accessible in any of the views you render.