我正在尝试从数据库中获取全站点全局设置,并在我的控制器中使用这些设置。
为了做到这一点,我在config目录下创建了一个自定义的global.php文件。 定义键=>值对。 试图使用DB :: table(....)facade获取值。
但它返回此错误:
尚未设置外观根。
我不能超越这个。
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')
]);
}
然后在控制器中你可以使用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));
}