Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pagination with cache in Laravel

Can anyone help me? I use redis cache. But I see same results on every pages when I use pagination. How can I fix it? Thanks.

like image 256
Mireli Eyyubzade Avatar asked Nov 28 '22 06:11

Mireli Eyyubzade


2 Answers

You should cache your results per page, with a key that is the current page.

$currentPage = request()->get('page',1);

$category = Cache::remember('sellcategory-' . $currentPage, 10, function(){
    return DB::table('elans')->orderBy('updated_at', 'desc')->where(['derc' => 1,'elaninnovu' => 'Satılır'])->paginate(10);
});
like image 68
thefallen Avatar answered Nov 30 '22 19:11

thefallen


This solution to cache and clear pagination caches.

How to cache:

$page = request()->get('page', 1);
$limit = request()->get('limit', 10);

$users = Cache::remember('admin' . $page, 10, function() use ($limit){
    return DB::table('users')->paginate($limit);
});

You can use a loop to check the prefix and delete them like this.

public static function forgetCaches($prefix)
{
    // Increase loop if you need, the loop will stop when key not found
    for ($i=1; $i < 1000; $i++) {
        $key = $prefix . $i;
        if (Cache::has($key)) {
            Cache::forget($key);
        } else {
            break;
        }
    }
}

Clear caches:

// Clear caches:
forgetCaches('admin');
like image 38
icaksama Avatar answered Nov 30 '22 20:11

icaksama