How to set global view variables using composer share in Laravel?

By Hardik Savani October 27, 2020 Category : Laravel

Everyone will have same situation sometimes, like we have some information that we need to access in all view files for example site title, login user information, footer information etc.

But, we can define global view variables using composer() of Laravel 6, laravel 7 and laravel 8. We just have to define value in AppServiceProvider and we can access that variable in every blade files. In bellow example i set "siteTitle" variable as global and i can access that variable in every view files.

You have to just open

AppServiceProvider.php and we can set variable as like bellow:

app/Providers/AppServiceProvider.php

namespace App\Providers;


use Illuminate\Support\ServiceProvider;


class AppServiceProvider extends ServiceProvider

{

/**

* Bootstrap any application services.

*

* @return void

*/

public function boot()

{

view()->composer('*', function ($view) {

$view->with('siteTitle', 'Itsolutionstuff.com');

});

}


/**

* Register any application services.

*

* @return void

*/

public function register()

{


}

}

Ok, now we can access "siteTitle" variable in every page like this way :

{{ $siteTitle }}

If you want to define global variable that can accessible in views, controllers, models etc then you have to follow this link : How to define Global Variables in Laravel 5?.