首页 > 解决方案 > Laravel 中缓存的分页问题:在每个页面上看到相同的结果

问题描述

我正在使用缓存,但是当我使用分页时,我在每个页面上看到相同的结果。我该如何解决?

对于创建、更新、编辑、保存,我使用 Laravel Model Observer。

我的邮政控制器

public function allpost(Request $request)
    {
        if($request->cache =='flush')
        {
            Cache::flush();
        }
        $data  =[];
        $posts =Cache::get('posts',[]);

        if(empty($posts))
        {
            $posts = Post::paginate(10);
            Cache::forever('posts',$posts);

        }
        $data['posts'] = $posts ;
        return view('frontend.allpost',$data);
    }

我的模型观察者

<?php
namespace App\Observers;
use Illuminate\Support\Facades\Cache;
class PostObserver
{
    public function created()
    {
        Cache::forget('posts');
    }

    public  function updated()
    {
        Cache::forget('posts');
    }
    public  function saved()
    {
        Cache::forget('posts');
    }

    public  function  deleted()
    {
        Cache::forget('posts');
    }
}

标签: laravelcachingpagination

解决方案


推荐阅读