Laravel 5.5 : How to define global variable that can be used in all controllers ?

给你一囗甜甜゛ 提交于 2020-04-11 05:57:06

问题


Hello Developers & Coders ,

My question is How to define a global variable , that can be used in all controllers in Laravel ?

I have defined one variable $company in AppServiceProviders's boot method - that im using in all blade views , but I can not use it in controllers file , it gives error , undefined variable $company

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        View::share('key', 'value');
        Schema::defaultStringLength(191);

        $company=DB::table('company')->where('id',1)->first();
        View::share('company',$company);  

    }

     /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }

}

please guide me , thanks for your efforts & time :)


回答1:


set configuration variables at runtime

class AppServiceProvider extends ServiceProvider
{
    /**
    * Bootstrap any application services.
    *
    * @return void
    */
    public function boot()
    {
        View::share('key', 'value');
        Schema::defaultStringLength(191);

        $company=DB::table('company')->where('id',1)->first();
        // View::share('company',$company);  
        config(['yourconfig.company' => $company]);
    }
}

usage:

config('yourconfig.company');



回答2:


Okay, so unless you want to keep it in your Session, which I absolutely do not recommend, Cache which does not seem to be a best idea either or set it through the Config system inside of a Framework (which already are 3 different solutions suited for different matters) I would start from thinking what that variable will contain, if that's something that's just a Collection of Company model then you can basically use it in any controller by just using Laravel Eloquent methods.

What I recommend is either $company = Company::where('foo', 'bar')->first();, or just some data provider that would return all the information that you need in the form of Laravel Collection.

tl;dr

#recommended way that's reusable throughout whole app
Company::find(1); // instead of DB::table('company')->where('id', 1)->get();

Hope that helps.



来源:https://stackoverflow.com/questions/51798773/laravel-5-5-how-to-define-global-variable-that-can-be-used-in-all-controllers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!