Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR PHP

define global variable in laravel blade

# 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 }}
 
PREVIOUS NEXT
Tagged: #define #global #variable #laravel #blade
ADD COMMENT
Topic
Name
9+3 =