Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Global Settings Model

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 change from the UI. My whole app uses a base.blade.php template that gets extended to the different views+controllers, this is where these settings would most likely be used.

Something like:

<h1><a href="#">{{ $setting->SiteName }}</a></h1>

I have the settings stored in a database table that are tied to a Setting.php model.

I'd rather not everyone of my controller methods query the database for these settings to just pass them up to the template base.blade.php.

What's the best way of creating some type of global setting variable I can reuse throughout the app?

Thanks in advance!

like image 461
Moose Avatar asked Sep 23 '15 16:09

Moose


People also ask

Where is .ENV file in Laravel?

In a fresh Laravel installation, the root directory of your application will contain a .env.example file that defines many common environment variables.

How get data from config file in Laravel?

We use the config() method to get values from files in the config directory. We use the dot notation to get the value we want. The first parameter we use is the file's name without the . php extension.

How do I turn on maintenance mode in Laravel 8?

Show activity on this post. I am using this command to enable maintenance mode php artisan down --secret="1630542a-246b-4b66-afa1-dd72a4c43515 . And then, I access my site with exapmple.com/1630542a-246b-4b66-afa1-dd72a4c43515 , to bypass the maintenance mode.


1 Answers

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:

<h1>{{ array_get(app('settings'), 'site.name') }}</h1>

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:

<h1>{{ setting('site.name') }}</h1>

Almost emulating the config() helper function’s usage.

like image 166
Martin Bean Avatar answered Sep 27 '22 15:09

Martin Bean