this is what i use
{{ $products->appends(request()->except('page'))->links() }}
and this is my controller
if ($request->get('sort') == 'sort-price_asc') {
$products = Product::whereIn('id', $product_ids)->published()->paginate(12);
$products = $products->sortBy(function ($prod) {
return ceil(($prod->packs->count() > 0 ? $prod->packs->sortBy('pivot.add_time')->first()->volume : 1) * $prod->price);
});
}
But why do I get an error
Method IlluminateDatabaseEloquentCollection::appends does not exist.
2
Answers
The method
appends()
comes from the Paginated collection. By usingsortBy()
, you’re turning that into a simple Eloquent Collection, which doesn’t have that method anymore.You should try to order the records BEFORE you call
->paginate()
.I see this order is pretty complex, so you may try to use raw queries for this.
The error "Method IlluminateDatabaseEloquentCollection::appends does not exist" occurs because you are trying to use the appends method on a collection ($products) instead of an instance of the Paginator class. The appends method is used for adding query parameters to the pagination links, and it is available on the Paginator instance, not on a regular collection.
In your code, you first fetch the products using the paginate method, which returns an instance of the Paginator class. However, in the next block of code, you overwrite the $products variable by sorting the collection using the sortBy method, which returns a new collection. Since the new collection is not a Paginator instance, the appends method is not available.
To fix this issue, you should perform the sorting operation on the Paginator instance itself before paginating the data. You can use the orderBy method to sort the data directly from the database query. Here’s how you can modify your code:
}