# Define Global Variables for Blade in Laravel 9
//1- Create a new service provider and call the share method within boot method
// app/Providers/ViewServiceProvider.php
<?php
namespace AppProviders;
use IlluminateSupportFacadesView;
use IlluminateSupportServiceProvider;
class ViewServiceProvider extends ServiceProvider
{
public function boot(): void
{
View::share('variableName', 'value');
}
}
//2- Register the service provider in the config/app.php file
<?php
return [
// ...
'providers' => [
// ..
AppProvidersViewServiceProvider::class,
],
];
//3- Clear configuration cache by using follwoing command
$ php artisan config:cache
//4- Now variable variableName can be used in all Blade templates
resources/views/users/index.blade.php
{{ variableName }}
SET configuration variables at runtime:
class AppServiceProvider extends ServiceProvider
{
public function boot()
{
View::share('key', 'value');
Schema::defaultStringLength(191);
$company=DB::table('company')->where('id',1)->first();
config(['yourconfig.company' => $company]);
}
}
USE:
config('yourconfig.company');
//create globals.php file in laravel/config/ and add the ff:
<?php
return [
'user_type' => [
'administrator' => 1,
'hr' => 2,
'employee' => 3
]
];
//then you can call it in your controllers or blade using
config('globals.user_type.employee')