Skip to content
Advertisement

Laravel 5.7: A facade root has not been set

I’m trying to get sitewide global settings from the database and use those settings in my controllers.

In order to do this I’ve created a custom global.php file under config directory.
Defined key=>value pairs.
Tried to get values using DB::table(….) facade.

But it returns this error:

A facade root has not been set.

I cannot get past beyond this.

config.php file as follows:

use IlluminateSupportFacadesDB;

return [ 

    'image_resize' => DB::table('settings')->where('id', 1)->value('image_resize'),
    'popup' => DB::table('settings')->where('id', 1)->value('popup'),
    'site_on' => DB::table('settings')->where('id', 1)->value('site_on')

];

Advertisement

Answer

You can use it

use IlluminateSupportFacadesConfig;

class AppServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap any application services.
     *
     * @return void
     */
    public function boot()
    {
        //
    }

    /**
     * Register any application services.
     *
     * @return void
     */
    public function register()
    {
        Config::set('global', [
            'image_resize' => DB::table('settings')->where('id', 1)->value('image_resize'),
            'popup' => DB::table('settings')->where('id', 1)->value('popup'),
            'site_on' => DB::table('settings')->where('id', 1)->value('site_on')
        ]);
    }

Then in controller you can use config('global.site_on')

Also you can use one query not three

public function register()
{
    $setting = DB::table('settings')
        ->where('id', 1)
        ->first(['popup', 'image_resize', 'site_on']);
    Config::set('global', [
        'image_resize' => $setting->image_resize,
        'popup' => $setting->popup,
        'site_on' => $setting->site_on
    ]);
}

Or more shortly code is

public function register()
{
    $setting = DB::table('settings')
        ->where('id', 1)
        ->first(['popup', 'image_resize', 'site_on']);
    Config::set('global', get_object_vars($setting));
}
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement