【问题标题】:Laravel 5.7: A facade root has not been setLaravel 5.7:尚未设置外观根
【发布时间】:2019-12-06 22:28:04
【问题描述】:

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

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

但它返回此错误:

外观根尚未设置

我无法超越这一点。

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

];

【问题讨论】:

  • 为什么不使用 .env 文件?
  • 您是否启用了app.php 文件中的外观?
  • @Adam:因为我想用我的控制面板重写这些设置。
  • @kuh-chan:是的,我在项目的其他几个控制器中使用 DB 外观。
  • 发生该错误是因为在 laravel 中首先注册了配置,然后是 Facades

标签: php laravel


【解决方案1】:

你可以使用它

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

然后在控制器中你可以使用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));
}

【讨论】:

  • 谢谢戴维特,我试过了,但它给出了这个错误:“找不到类'App\Providers\Config'”
  • 添加use Illuminate\Support\Facades\Config;查看更新答案
  • @megavolkan 你试试吗??
  • 是的,我有,而且效果很好。除了短代码不起作用。它会抛出一个错误,提示“get_bject_vars(setting) 方法中未定义常量“设置”。我用过长版,它可以工作。谢谢@Davit。
  • 试试this Config::set('global', get_object_vars($setting));一定是$setting我忘了$
【解决方案2】:

我在摆弄我的 app/config.php 文件后遇到了这个问题。我添加了一些选项,不小心在它后面放了一个分号而不是逗号。 我有:

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

将其更改为正确的逗号,一切都按预期工作。

【讨论】:

    猜你喜欢
    • 2020-05-18
    • 2020-03-23
    • 2018-03-09
    • 2020-09-10
    • 2020-01-10
    • 1970-01-01
    • 1970-01-01
    • 2020-05-11
    • 2021-09-20
    相关资源
    最近更新 更多