i've ever asked this question before in codeigniter, now I want to ask about this in laravel.
I want to set a global variable for custom helpers, models, and controllers the variable is got from database result..
Here is the example:
don't know where to put the variable
$data= DB::table('categories')->where('id', '2')->first(); $this->product_var = $data->product; **//main global variable**
custom helper
function test() { if($this->product_var=="product name") { } }
my controller
function index() { echo $this->product_var; }
my model
function get_data() { echo $this->product_var; }
As you can see my scripts above, $this->product_var
is almost used for custom helper
, my controller
, and my model
. in codeigniter we create Globals.php in libraries folder, or just put the variable in core controllers. Where should i set the global variable?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With