Laravel - Set global variable from settings table

前端 未结 3 1457
渐次进展
渐次进展 2020-12-13 22:52

I\'m trying to store all my settings from my settings table into a global variable, but I\'m stucked now(I have no idea what\'s the next step), this is my actua

相关标签:
3条回答
  • 2020-12-13 23:05

    See improved answer in Update 2

    I would add a dedicated Service Provider for this. It will read all your settings stored in the database and add them to Laravels config. This way there is only one database request for the settings and you can access the configuration in all controllers and views like this:

    config('settings.facebook');
    

    Step 1: Create the Service Provider.

    You can create the Service Provider with artisan:

    php artisan make:provider SettingsServiceProvider

    This will create the file app/Providers/SettingsServiceProvider.php.

    Step 2: Add this to the boot-method of the provider you have just created:

    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot()
    {
        // Laravel >= 5.2, use 'lists' instead of 'pluck' for Laravel <= 5.1
        config()->set('settings', \App\Setting::pluck('value', 'name')->all());
    }
    

    From the Laravel Docs:

    [The boot method] is called after all other service providers have been registered, meaning you have access to all other services that have been registered by the framework.

    http://laravel.com/docs/5.1/providers#the-boot-method

    Step 3: Register the provider in your App.

    Add this line to the providers array in config/app.php:

    App\Providers\SettingsServiceProvider::class,
    

    And that's it. Happy coding!

    Update: I want to add that the boot-method supports dependency injection. So instead of hard coding \App\Setting, you could inject a repository / an interface that is bound to the repository, which is great for testing.

    Update 2: As Jeemusu mentioned in his comment, the app will query the database on every request. In order to hinder that, you can cache the settings. There are basically two ways you can do that.

    1. Put the data into the cache every time the admin is updating the settings.

    2. Just remember the settings in the cache for some time and clear the cache every time the admin updates the settings.

    To make thinks more fault tolerant, I'd use the second option. Caches can be cleared unintentionally. The first option will fail on fresh installations as long as the admin did not set the settings or you reinstall after a server crash.

    For the second option, change the Service Providers boot-method:

    /**
     * Bootstrap the application services.
     *
     * @param \Illuminate\Contracts\Cache\Factory $cache
     * @param \App\Setting                        $settings
     * 
     * @return void
     */
    public function boot(Factory $cache, Setting $settings)
    {
        $settings = $cache->remember('settings', 60, function() use ($settings)
        {
            // Laravel >= 5.2, use 'lists' instead of 'pluck' for Laravel <= 5.1
            return $settings->pluck('value', 'name')->all();
        });
    
        config()->set('settings', $settings);
    }
    

    Now you only have to make the cache forget the settings key after the admin updates the settings:

    /**
     * Updates the settings.
     *
     * @param int                                 $id
     * @param \Illuminate\Contracts\Cache\Factory $cache
     *
     * @return \Illuminate\Http\RedirectResponse
     */
    public function update($id, Factory $cache)
    {
        // ...
    
        // When the settings have been updated, clear the cache for the key 'settings':
        $cache->forget('settings');
    
        // E.g., redirect back to the settings index page with a success flash message
        return redirect()->route('admin.settings.index')
            ->with('updated', true);
    }
    
    0 讨论(0)
  • 2020-12-13 23:28

    To avoid querying the database on each request, you should save the settings to a config file each time they are changed by the admin/user.

        // Grab settings from database as a list
        $settings = \App\Setting::lists('value', 'name')->all();
    
        // Generate and save config file
        $filePath = config_path() . '/settings.php';
        $content = '<?php return ' . var_export($settings, true) . ';';
        File::put($filePath, $content);
    

    The above will create a Laraval compatible config file that essentially just returns an array of key => values. The generated file will look something like this.

    <?php 
    
    return array(
        name => 'value',
        name => 'value',
    );
    

    Any php file in the /config directory will be auto-included by Laravel and the array variables accessible to your application via the config() helper:

    config('settings.variable_name');
    
    0 讨论(0)
  • 2020-12-13 23:28

    You can store the data in the database just like you do it normally in Laravel. \App\Setting::create(), \App\Setting::new() and other methods.

    For using the values in blade, you can do {{\App\Setting::where('name','title')->pluck('value')}}

    And, you can also use scopes for this.

    class Setting extends Model
    {
        public function scopeFor($query, $settingName)
        {
            return $query->where('name', $settingName);
        }
    }
    

    then you could use \App\Setting::for('title')->pluck('value')

    0 讨论(0)
提交回复
热议问题