php - 拉维尔 5.7 : A facade root has not been set

标签 php laravel

我正在尝试从数据库中获取站点范围的全局设置并在我的 Controller 中使用这些设置。

为了做到这一点,我在 config 目录下创建了一个自定义的 global.php 文件。
定义的键=>值对。
尝试使用 DB::table(....) 外观获取值。

但是它返回这个错误:

A facade root has not been set.

我不能超越这个。

config.php文件如下:

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

];

最佳答案

你可以使用它

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

然后在 Controller 中你可以使用config('global.site_on')

你也可以使用一个查询而不是三个

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

或者更简短的代码是

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

关于php - 拉维尔 5.7 : A facade root has not been set,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55129389/

相关文章:

php - Mysql连接类

php - 为什么 1024 * 1024 * 1024 * 1024 * 1024 返回 float ?

database - Schema Facade 中的 DB::reconnect()?

php - Paypal验证任意支付

PHP MySQL 只删除存在的记录

php - SQLSTATE[HY000] : General error: 1364 Field 'parent_id' doesn't have a default value

php - Laravel 下的负载均衡器 + 集中式 Redis session 服务器

Laravel eloquent - 多对多,选择只匹配多表

php - 函数加密AES-256-CBC,搜索mysql

php - 无法在 Laravel Dusk 中截图