Laravel load settings from database
IMHO it's a bit over engineered. You can do the same with the helper approach:
function settings($key)
{
static $settings;
if(is_null($settings))
{
$settings = Cache::remember('settings', 24*60, function() {
return array_pluck(App\Setting::all()->toArray(), 'value', 'key');
});
}
return (is_array($key)) ? array_only($settings, $key) : $settings[$key];
}
Less cumbersome. No loops. Max 1 DB hit per request. Max 1 Cache hit per request.
Here is an updated answer as of Laravel 5.5.
First, create a migration for your settings
table:
Schema::create('settings', function (Blueprint $table) {
$table->increments('id');
$table->string('key');
$table->text('value')->nullable();
$table->timestamps();
});
Then create a Setting
model:
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class Setting extends Model
{
protected $fillable = ['key', 'value'];
}
Now, in AppServiceProvider
, add the following to your boot()
method:
if (Schema::hasTable('settings')) {
foreach (Setting::all() as $setting) {
Config::set('settings.'.$setting->key, $setting->value);
}
}
This will create config('settings.*')
for each setting in your database, where *
is the key.
For example, insert/create the following setting:
Setting::create([
'key' => 'example',
'value' => 'Hello World',
]);
Now you can access config('settings.example')
, which will give you Hello World
.
Updating settings is as simple as doing:
Setting::where('key', 'example')->update([
'value' => 'My New Value',
]);