How to share data to every blade view in Laravel application? We will use ViewServiceProvider!

If you want to share some data across all (or specific) views in your Laravel application here is easy way how to achieve this.

 

Let's say we want to share logged in user data, but not only from User table but also from User pivot tables as well.

To achieve this goal we will create custom ViewServiceProvider and then by using View::composer we will attach our user data. So, let's begin:

 

1. Create ViewServiceProvider and register it

to create service provider we will use artisan command:

                    php artisan make:provider ViewServiceProvider
                  

New provider is stored in App\Providers and we need to register it. Open config/app.php and add this line to 'providers' section:

                    'providers' => [
...
App\Providers\ViewServiceProvider::class,
...
],
                  

 

2. Share user data to all views from  our ViewServiceProvider

Open our newly created ViewServiceProvider and add this to our boot() method:

                    public function boot()
    {
        View::composer('*', function ($view) {
            $view->with('authUserData', User::where('id','=',auth()->id())->first());
        });
    }
                  

 

3. Use shared auth user data in any view

In order to get any user data in our views we can use $authUserData variable:

                    {{$authUserData->email}}
                  

 

But since we are returning complete User model, we can access to any User connected tables. So let's say that users first name is stored in user_details table which is connected with user table by foreign key and we already have set up connection in User model like this:

                    public function userDetail() {
        return $this->hasOne('App\Http\Models\UserDetails', 'user_id' ) ;
    }
                  

So now, if we want to access first name in our view, all we need to do is this:

                    {{$authUserData->userDetail->firstName}}
                  

 

 

If you don't want to share data with all views, you can define view which will have access to this data. Back in our ViewServiceProvider we can change boot method to something like this:

                    public function boot()
    {
        View::composer('dashboard', function ($view) {
            $view->with('authUserData', User::where('id','=',auth()->id())->first());
        });
    }
                  

and data will be shared only with view named 'dashboard'. More info you can find in official documentation:

https://laravel.com/docs/5.8/views#sharing-data-with-all-views