Global variable in laravel controller

后端 未结 3 735
Happy的楠姐
Happy的楠姐 2020-12-30 08:05

I want the $year variable to be available in all functions of my PagesController. I tried this code but I didn\'t succeed.



        
3条回答
  •  清歌不尽
    2020-12-30 08:38

    You can create a global singleton within App::before event

    App::before(function($request) {
        App::singleton('customYear', function(){
            $dt = Carbon::parse();
            $customYear = $dt->year;
            return $customYear;
        });
    
        // If you use this line of code then it'll be available in any view
        View::share('customYear', app('customYear'));
    
        //To get the same data in any controller you may use:
        $customYear = app('customYear');
    });
    

提交回复
热议问题