I would like to know if there is any way to page this query that I do in Laravel and store it in the cache.
I’ve already put ->paginate()
but it seems that the cache doesn’t return in Eloquent but as an object. I checked the variable’s type with gettype()
.
this is my role. Can anyone help me?
public function getProductsRecommendations($keywords)
{
$expiration = 10;
$keyName = 'productsRecommended';
$list = Cache::remember($keyName, $expiration, function () use ($keywords) {
return Product::query()->where(function ($productsAll) use ($keywords) {
if ($keywords) {
foreach ($keywords as $keyword)
$productsAll->orWhere('title', 'LIKE', '%' . $keyword . '%')->orWhere('description', 'LIKE', '%' . $keyword . '%')->orWhere('code', 'LIKE', '%' . $keyword . '%');
}
})->where('status', 'active')->get();
});
return $list;
}
2
Answers
I managed to do what I needed. I'll leave it here in case someone goes through the same problem and finds this question.
Sometimes you might want to create an instance of paging manually, passing in an array of items. You can do this by creating an
IlluminatePaginationPaginator
orIlluminatePaginationLengthAwarePaginator
instance, depending on your needs.To exemplify:
You should cache your results per page, with a key that is the current page. Something like: