global variable for all controller and views

后端 未结 16 2114
Happy的楠姐
Happy的楠姐 2020-11-27 15:54

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

public function __construct() 
{
             


        
16条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 16:03

    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.

提交回复
热议问题