eylay
eylay

Reputation: 2160

how to paginate after a sort by in laravel

I have a Food model. Each food has a price and a discount (in percent). I have appended a cost attribute to hold a value which is calculated base on the first price and discount.

Example:
We have a Food with a price of 10$. discount is 10%, so the cost is 9$.

class Food extends Model
{
    protected $appends = ['cost'];

    public function getCostAttribute()
    {
        return $this->price - round( ($this->price*$this->discount) / 100 );
    }

}

I need to order my foods based on cost. I cannot use orderBy because cost is not actually a column. so I have to use sortBy.

$foods = Food::all();
$foods = $foods->sortBy(function($food){
    return $food->cost;
});

Now, how can I paginate $foods variable? Because I cannot execute following code to paginate

$foods = $foods->paginate(12);

Upvotes: 1

Views: 1318

Answers (2)

TsaiKoga
TsaiKoga

Reputation: 13394

sort by has already take datas from db, so use pagination is not really helpful.

So I recommend to change your code like this, this will reduce IO cost:

Food::select('*', 
             DB::raw('(price - round((price * discount) / 100)) AS cost')
            )->orderBy('cost')
             ->paginate(12)

Upvotes: 5

Qonvex620
Qonvex620

Reputation: 3972

You have to use join to sort your item base on the relationship model. Try this

$order = 'desc';
$users = Food::join('costs', 'foods.id', '=', 'costs.id')->orderBy('costs.id', 
$order)->select('foods.*')->paginate(10);

reference : [https://laracasts.com/discuss/channels/eloquent/order-by-on-relationship][1]

Upvotes: 0

Related Questions