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

By Hardik Savani | July 8, 2016 | | 2848 Viewer | Category : Laravel


Share this post:

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. 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?.



We are Recommending you: