How to set global view variables using composer in Laravel?

Today now in this post i will show you How to set global view variables using composer share in Laravel? We are face the same situation sometimes, as like we need to some information about that sometimes we need to access in all the view files. For example site title, login user information, footer information etc.

But, you can define as global view variables by using composer() in Laravel 6, laravel 7 and laravel 8 any version. Just we need to define the value in AppServiceProvider and then you can access that variable in every the blade files.

Now in bellow example i will set “siteTitle” variable as a global and then we can access that variable in every view files in your project. Just we need to just open AppServiceProvider.php and we need to set variable as like as 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 you can access the “siteTitle” variable in every blade file as like this way :

{{ $siteTitle }}

Read Also : How to Create Custom Blade Directive in Laravel?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About Shahriar Sagor

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by Shahriar Sagor →