Search code examples
phplaravelglobal-variableslaravel-5.5controllers

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


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 :)


Solution

  • 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');