Home > Back-end >  Sorting products by discount percentage
Sorting products by discount percentage

Time:01-12

I am trying to sort products by discount percentage in my laravel app. I have two columns in my products table i.e. price, discount_price. How can I order order them so that products with higher discount shows up higher in order. I've tried following but it doesn't work

$products = DB::table('products')->get();
$sorted_products = $products->sortBy('price - discount_price');

Any pointers plz, thanks.

CodePudding user response:

You can use the select method and DB::raw to add a RAW SQL component to the query. Assunming that discount is the discount in currency units we are interested in fetching all the fields (*) plus the calculated field price - discount which we will call real_price.

$sorted_products = DB::table('product')
                       ->select(DB::raw("*, price - discount as real_price"))
                       ->orderBy("real_price")
                       ->get();

This will build the following SQL query and execute it:

SELECT *, price - discount as real_price FROM product ORDER BY real_price;

If the discount is as percentage you could:

$sorted_products = DB::table('product')
                       ->select(DB::raw("*, price * discount as real_discount"))
                       ->orderBy("real_discount")
                       ->get();

Which would be ordered by higher discount value.

  •  Tags:  
  • Related