skip to Main Content

I use this query:

$category = Category::whereStatus(1)->first();

    $d = $category->products()->get(['id', 'price', 'status']);
    $d = $d->where('price', '>', 0)->where('status',1)->sortByDesc('price');
    return $d->values()->paginate(16);

Category Model:

public function products()
{
    return $this->belongsToMany(Product::class);
}

But show this error:

BadMethodCallException
Method IlluminateDatabaseEloquentCollection::paginate does not exist.

How to issue this query?

2

Answers


  1. ->get() returns a Collection, so your second line is working off the collection. You cannot paginate a collection. Instead, merge all 3 lines into 1 query builder query:

    $d = $category->products(); // $d is now a query builder object
    // More where's. You can chain this if you want
    $d = $d->where('price', '>', 0)->where('status',1)->orderByDesc('price'); 
    return $d->select(['id', 'price', 'status'])->paginate(16);
    
    Login or Signup to reply.
  2. $category = Category::whereStatus(1)->first();
    
    $productsQuery = $category->products()->where('price', '>', 0)
        ->where('status', 1)->orderByDesc('price');
    
    // Use the paginate method on the query, not on the collection
    $perPage = 16;
    return $productsQuery->paginate($perPage);
    

    Error: Do not use paginate after get
    We use the paginate method on the query builder ($productsQuery) to paginate the results. This will return a paginated set of results, which you can return from your controller.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search