Cache table values globally in laravel

谁都会走 提交于 2019-12-22 10:57:08

问题


I have a table: settings with the model Setting

class Setting extends Model
{
    protected $fillable = [
        'name', 'value',
    ];
}

I have created a service provide SettingsServiceProvider and registered in app.php

class SettingsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot(Factory $cache, Setting $settings)
    {
        if (\Schema::hasTable('settings')) {
            config()->set('settings', Setting::pluck('value', 'name')->all());
        }
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {

    }
}

After adding the name and value to the table settings, I am calling it in the view like this:

{{ config('settings.sitename') }}

Where sitename is the name field which returns the value perfectly.

Problem: The problem with this method is that with every page request makes a DB call. And as these settings are not meant to be changed frequently, so I was looking for a method to cache it in the laravel cache.

I tried the following:

class SettingsServiceProvider extends ServiceProvider
{
    /**
     * Bootstrap the application services.
     *
     * @return void
     */
    public function boot(Factory $cache, Setting $settings)
    {
        $settings = $cache->remember('settings', 60, function() use ($settings)
        {
        return $settings->pluck('name', 'value')->all();
        });
        config()->set('settings', $settings);

        /* if (\Schema::hasTable('settings')) {
            config()->set('settings', Setting::pluck('value', 'name')->all());
        } */
    }

    /**
     * Register the application services.
     *
     * @return void
     */
    public function register()
    {
        //
    }
}

But when I try to return it to the view like this:

{{ config('settings.sitename') }}

nothing gets return.


回答1:


I don't have enough reputation to comment on the post but this should solve it

Replace:

return $settings->pluck('name', 'value')->all();

With:

return $settings->pluck('value', 'name')->all();

and then with the usual:

php artisan config:clear
php artisan cache:clear



回答2:


In command prompt, just type

php artisan 

OR

 php artisan list

It gives list of command with Explanation which help u lot

Thank you.



来源:https://stackoverflow.com/questions/43753072/cache-table-values-globally-in-laravel

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!