global variable in laravel

26,204

Solution 1

Sounds like a good candidate for a configuration file.

Create a new one, let's call it calculations.php:

Laravel ~4ish:

app
    config
        calculations.php

Laravel 5,6,7+:

config
    calculations.php

Then put stuff in the new config file:

<?php return [ 'some_key' => 42 ];

Then retrieve the config in your code somewhere (note the file name becomes a "namespace" of sorts for the config item):

echo Config::get('calculations.some_key'); // 42 in Laravel ~4
echo config('calculations.some_key'); // 42 in Laravel ~5,6,7+

Solution 2

Set a property on the BaseController, which should be located in your controllers directory.

Your controllers should extend the BaseController class and thus inherit its properties.

Share:
26,204
Pars
Author by

Pars

Web and Mobile Developer at Chista Group. Prior lead Web Developer and Mobile Developer at Fanavari Tandis. Prior Web Developer at Lifeweb co. Prior Web Developer at Caspian co. Prior lead Web Developer at Padafand IT.

Updated on July 20, 2022

Comments

  • Pars
    Pars almost 2 years

    In PHP, I used to define some variables in my header.php and use them in all my pages. How can I have something like that in Laravel?

    I am not talking about View::share('xx', 'xx' );

    Assume I want to have a variable which holds a number in it and I need this number inside all my controllers to calculate something.