Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

global variable for all controller and views

In Laravel I have a table settings and i have fetched complete data from the table in the BaseController, as following

public function __construct()  {     // Fetch the Site Settings object     $site_settings = Setting::all();     View::share('site_settings', $site_settings); } 

Now i want to access $site_settings. in all other controllers and views so that i don't need to write the same code again and again, so anybody please tell me the solution or any other way so i can fetch the data from the table once and use it in all controllers and view.

like image 861
Deepak Goyal Avatar asked Aug 07 '14 18:08

Deepak Goyal


People also ask

Can a global variable be used anywhere?

You can access the global variables from anywhere in the program. However, you can only access the local variables from the function. Additionally, if you need to change a global variable from a function, you need to declare that the variable is global. You can do this using the "global" keyword.

What are the two types of global variables?

A global variable can be classified as either session or database based on the scope of the value: The value of a session global variable is uniquely associated with each session that uses this particular global variable. Session global variables are either built-in global variables or user-defined global variables.


1 Answers

Okay, I'm going to completely ignore the ridiculous amount of over engineering and assumptions that the other answers are rife with, and go with the simple option.

If you're okay for there to be a single database call during each request, then the method is simple, alarmingly so:

class BaseController extends \Controller {      protected $site_settings;      public function __construct()      {         // Fetch the Site Settings object         $this->site_settings = Setting::all();         View::share('site_settings', $this->site_settings);     }  } 

Now providing that all of your controllers extend this BaseController, they can just do $this->site_settings.

If you wish to limit the amount of queries across multiple requests, you could use a caching solution as previously provided, but based on your question, the simple answer is a class property.

like image 86
ollieread Avatar answered Sep 19 '22 11:09

ollieread