Laravel Global Settings Model

后端 未结 2 1242
梦如初夏
梦如初夏 2021-01-03 00:44

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

2条回答
  •  心在旅途
    2021-01-03 01:09

    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.

提交回复
热议问题