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

About Us:

We are from free coder. We are a group of web developers who are passionate about web development. You can learn from us php, laravel, node js, vue js, react js and many other topic on web developement.
we are very happy to help you.
free coder

Today what you are going to learn:

Everyone will have same situation sometimes, like we have some information that we need to access in all view files for lesson 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 lesson 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?.

Recent Posts

Related Posts