Skip to content
Advertisement

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);
}

Advertisement

Answer

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 IlluminateSupportFacadesDB;

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

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement