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
->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: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.