I\'m working on building a small CRUD app in Laravel 5. I have a few app wide settings such as \"SiteTitle\" and \"BaseURL\" I\'d like to give my admins the ability to chang
You could create a service provider, say SettingsServiceProvider
, that loads all the settings from the database and then caches them. Then on subsequent page loads, it could return cached setting values rather than querying the database, which you should be rightfully concerned about.
Something as simple as:
class SettingsServiceProvider extends ServiceProvider
{
/**
* Register the application services.
*
* @return void
*/
public function register()
{
$this->app->singleton('settings', function ($app) {
return $app['cache']->remember('site.settings', 60, function () {
return Setting::pluck('value', 'key')->toArray();
});
});
}
}
Assuming your settings model is called Setting
as per Laravel’s naming conventions. You can then access settings like so:
{{ array_get(app('settings'), 'site.name') }}
If you wanted a prettier way of accessing settings, you could create a helper function:
function setting($key)
{
return array_get(app('settings'), $key);
}
Which would make usage like this:
{{ setting('site.name') }}
Almost emulating the config()
helper function’s usage.