Define Global Variables for Blade Templates in Laravel 9

Define Global Variables for Blade Templates in Laravel 9

There might be a case that the same variable should be passed to all Blade templates. It can be done on each controller. However, it is not a perfect solution. This tutorial shows how to define global variables for Blade templates in Laravel 9 application.

The View facade has the share method which allows injecting a variable to each Blade template. Create a new service provider and call the share method within boot method.



namespace App\Providers;

use Illuminate\Support\Facades\View;
use Illuminate\Support\ServiceProvider;

class ViewServiceProvider extends ServiceProvider
    public function boot(): void
        View::share('trackingId', 'XXXXX-YYYYY-ZZZZZ');

Register the service provider in the config/app.php file.



return [
    // ...
    'providers' => [
        // ..


Clear configuration cache using command:

php artisan config:cache

Now variable trackingId can be used in all Blade templates.


{{ $trackingId }}

Leave a Comment

Cancel reply

Your email address will not be published.