简体   繁体   中英

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 Illuminate\Support\Facades\DB;

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

];

You can use it

use Illuminate\Support\Facades\Config;

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));
}

I ran into this problem after I was fiddling with my app/config.php file. I added some options and accidentally put a semi-colon instead of a comma after it. I had:

'vapid_public_key'   => env('VAPID_PUBLIC_KEY'); <--- offending semi-colon
'vapid_private_key'  => env('VAPID_PRIVATE_KEY'),

Changed it to the proper comma and everything works as expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM