skip to Main Content

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


  1. The method appends() comes from the Paginated collection. By using sortBy(), 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.

    Login or Signup to reply.
  2. 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:

    if ($request->get('sort') == 'sort-price_asc') {
    $products = Product::whereIn('id', $product_ids)
        ->published()
        ->orderByRaw('price * volume ASC')
        ->paginate(12);
    
    $products->each(function ($prod) {
        $volume = $prod->packs->count() > 0 ? $prod->packs->sortBy('pivot.add_time')->first()->volume : 1;
        $prod->calculated_price = ceil($volume * $prod->price);
    });
    

    }

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