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.
<?php
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.
<?php
return [
// ...
'providers' => [
// ..
App\Providers\ViewServiceProvider::class,
],
];
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