Joseph
Joseph

Reputation: 6259

can't use paginate when use sortby in Laravel

I Want to get products and sort it by mutator attribute in my case it's called price

i search for how to sort it and found that i can use sortBy from the collection

like that

private function search()
{   
    return Product::with(['firstImage', 'category'])
        ->sortBy('price');
}

it works fine, but when I try to add paginate nothing happens and there is no paginate in the response

private function search()
{   
    return Product::with(['firstImage', 'category'])
        ->paginate(9)->sortBy('price');

}

So how can i add paginate in this case?

Edit

price mutator

public function getPriceAttribute()
{
    return $this->sell_price - (($this->discount * $this->sell_price) / 100);
}

Upvotes: 2

Views: 1236

Answers (2)

Majid Jalilian
Majid Jalilian

Reputation: 138

You must use paginate(9) after orderBy() function. So you must edit second code like this :

private function search()
{   
    return Product::with(['firstImage', 'category'])
        ->orderBy('price')->paginate(9);

}

Upvotes: 2

Hafez Divandari
Hafez Divandari

Reputation: 9029

Unfortunately there is no way to call paginate() on collection. You may manually paginate the collection result or modify your query and use addSelect or orderByRaw to include mutated value:

use Illuminate\Support\Facades\DB;

Product::select('*', DB::raw('(sell_price - ((discount * sell_price) / 100)) AS price'))
        ->orderBy('price')
        ->paginate(9);

By the way, I think you'll get the same result to order by sell_price column instead of price mutated value if your discount is a constant value, so try orderBy('sell_price') instead of sortBy('price'):

Product::with(['firstImage', 'category'])
        ->orderBy('sell_price')
        ->paginate(9);

Laravel Docs: https://laravel.com/docs/master/queries#ordering-grouping-limit-and-offset

Upvotes: 2

Related Questions