Laravel set global variable for all custom helpers,controllers, and models Laravel set global variable for all custom helpers,controllers, and models codeigniter codeigniter

Laravel set global variable for all custom helpers,controllers, and models


Like @Mozammil mentioned:

The idea is to use the "Laravel configurations". This allows you to keep values in global scope for one request cycle.

You can access these value through out the application using the config() helper of Laravel.

You just need to set it once like:

config(['app.product_data' => $data]);

And, this will be available for you globally in the application just use config('app.product_data') to access the data.

Like:

In custom helper

function test() {    if(config('app.product_data')->product_var=="product name") {         //do something    }}

Your controller

function index() {    echo config('app.product_data')->product_var;}

Your model

function get_data() {     return config('app.product_data')->product_var;}

Hope this would help.


Config is not a good way to hold a global variable. As the framework suggests config should only contain configuration for your project. And they should be independent of request.

Laravel provides much better way to handle global variables, you can use Singletons. Why?Because a singleton holds on to application a deepest level, it can be called and available at in part of request. Once declared its pretty hard to change singleton in the middle of request.

You can put this code in Your AppServiceProvider or you can create your own ProductVarServiceProvider.

App::singleton('product_var', function(){     return DB::table('categories')->where('id', '2')->first();}); 

This is way you can we sure about the origin of product_var. Later you can use helper function app('product_var') anywhere in you code.

You should be careful when declaring global variables.


I recently answered a question whereby the author had a very nice way of globally caching table values.

The idea is that he was fetching table values (also caching it) and he made a Settings ServiceProvider to be able to access it as a configuration variable later on.

Maybe this would work out very well for you too.