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