global variable for all controller and views

后端 未结 16 2134
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:19

    At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):

    // You can keep this in your filters.php file
    App::before(function($request) {
        App::singleton('site_settings', function(){
            return Setting::all();
        });
    
        // If you use this line of code then it'll be available in any view
        // as $site_settings but you may also use app('site_settings') as well
        View::share('site_settings', app('site_settings'));
    });
    

    To get the same data in any controller you may use:

    $site_settings = app('site_settings');
    

    There are many ways, just use one or another, which one you prefer but I'm using the Container.

提交回复
热议问题