skip to Main Content

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


  1. Chosen as BEST ANSWER

    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 or IlluminatePaginationLengthAwarePaginator instance, depending on your needs.

    To exemplify:

    use IlluminatePaginationPaginator;
    
    $paginator = new Paginator($array, $rowPerPage, $currentPage = null);
    

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

    $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);
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search