Search code examples
phplaravelglobal-variables

How to make a global variable for all blade laravel


Good Peoples.

I have an issue with my project.

In the layout blade, I need to fetch some data from the database. But I cannot pass variables as there has no route for the layout blade. It's just a master blade.

Is there any way to make a global variable and use it all blade?

Thanks for the valuable replies.


Solution

  • to have global functions or variables there are different ways in my opinion, the easiest way is:

    make a helper php file to restore global functions and vars, in this way you load this file in composer.json and you can call that everywhere you want.

    I created Functions.php in App/Helpers directory to restore my global vars and functions.

    after that declare the file in composer.json: "autoload", inside it if there is not "files(array)" add it and set the path to your file. in my example, it is "app/Helpers/Functions.php".

    "autoload": {
            "psr-4": {
                "App\\": "app/",
                "Database\\Factories\\": "database/factories/",
                "Database\\Seeders\\": "database/seeders/"
            },
            "files": [
                "app/Helpers/Functions.php"
            ]
        },
    

    enter image description here

    finally, rerun the

    php artisan serve
    

    for accessing a variable in your blade, I'm not sure you can do it or not (I tried but it returns undefined variable).

    you can do:

    // in your helper file
    myFunc() {
        $myVar = 'value';
        return $myVar;
    }
    
    // in your blade
    {{ myFunc() }}
    

    or using classes:

    // in your helper file
    class myClass {
        protected $myVar = 'value';
        protected static $staticVar = 'value';
    
        public myFunc() {
            return $this->myVar;
        }
    
        public static staticFunc() {
            return myClass::$staticVar;
        }
    }
    
    // in your blade
    {{ (new myClass())->myFunc() }}
    // of static function
    {{ myClass::staticFunc() }}
    

    hope, it helps...