在Laravel中全局缓存表值 [英] Cache table values globally in laravel

查看:280
本文介绍了在Laravel中全局缓存表值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一张桌子:型号为Setting

I have a table: settings with the model Setting

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

我已经创建了一个服务提供SettingsServiceProvider,并已在app.php

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()
    {

    }
}

在表settings中添加namevalue之后,我在这样的视图中调用它:

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

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

sitenamename字段,可以完美地返回值.

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

问题: 这种方法的问题在于,每个页面请求都会发出一个DB调用.由于这些设置并不经常更改,因此我一直在寻找一种将其缓存在laravel缓存中的方法.

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.

我尝试了以下操作:

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') }}

一无所获

推荐答案

我没有足够的声誉来评论该帖子,但这应该可以解决

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

替换:

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

使用:

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

,然后按照通常的方式进行操作:

and then with the usual:

php artisan config:clear
php artisan cache:clear

这篇关于在Laravel中全局缓存表值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆