احمدرضا نوزعیم
2 سال پیش توسط احمدرضا نوزعیم مطرح شد
0 پاسخ

مشکل تعامل Cache - Paginate و Lazy در لاراول

من میخواستم برای اینکه صفحه ی مقالاتم بهینه تر بشه به جای get از Lazy استفاده کنم و مشکلی نداشت و همه چیز با paginate کردن کالکشن Lazy خوب کار میکرد.
حالا اومدم cache رو بهش اضافه کنم که هربار کوئری نزنم: این کدی بود که نوشته بودم

protected function getArticles(): LengthAwarePaginator
{
        //if in trash can
            $query = Article::with('media')->latest();
        //make a lazy collection and paginate
        return Help::paginate($query->lazy() , 20);
}

public function index()
{
//if we have cache //get cache //if not make cache
$articles = Cache::remember('articles' , config('cache.ttl' , 60 * 15) , function (){
      return $this->getArticles();
});
}

اما مشکل اینجا بود که currentpage داخل cache رفته بود و وقتی تغییر صفحه میدادم هنوز فک میکرد صفحه 1 هستیم.
برای همین اینطوری paginate رو از cache خارج کردم:

protected function getArticles()
{
        //if in trash can
            $query = Article::with('media')->latest();
        //make a lazy collection and paginate
        return $query->lazy();
}

public function index()
{
//if we have cache //get cache //if not make cache
$articles = Cache::remember('articles' , config('cache.ttl' , 60 * 15) , function (){
      return $this->getArticles();
});
Help::paginate($articles , 20);
}

حالا برای cache ارور میده :

Serialization of 'Closure' is not allowed

این مشکل در cache زمان put اتفاق میوفته.
از هوش مصنوعی کمک گرفتم گفت باید LazyCollection رو تبدیل به Collection کنی
نتیجه شد و جواب داد:

     return collect($query->lazy());

اگه روش دیگه ای سراغ دارین یا تجربه ای دارید که مرتبط باشه ممنون میشم به اشتراک بذارین.