Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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 image 382
Willyanto Halim Avatar asked May 22 '17 07:05

Willyanto Halim


2 Answers

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.

like image 173
Parantap Parashar Avatar answered Sep 24 '22 11:09

Parantap Parashar


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.

like image 40
anwerj Avatar answered Sep 21 '22 11:09

anwerj