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.
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.
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.
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.
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