my product table contains these datas
id | name | price | discounted_price |
---|---|---|---|
I want to apply sorting to table product using laravel eloquent. the discounted_price is 0 then sorting apply to price. discounted_price not 0 then sorting apply to discounted_price.
CodePudding user response:
You can simply retrieve all items using Eloquent get()
method. After that, iterate through the collection and at each iteration, check if the discounted_price
is != 0
. If the condition is true, simply append a new item called final_price
to the collection, with the value of discounted_price
. Else, append the final_price
with the price
.
Finally, use sortBy()
method to sort the collection by the final_price
$products = Product::get();
foreach($products as $product) {
if($product->discounted_price != 0) {
$product->final_price = $product->discounted_price;
} else {
$product->final_price = $product->price;
}
}
return $products->sortBy(['final_price','asc']);
Further reference on collections sorting - https://laravel.com/docs/9.x/collections#method-sortby
CodePudding user response:
You can do this :
$products = Product::all();
return $products->map(function ($product) {
$isDiscountPrice = $product->discounted_price !== 0;
$product->final_price = $product->{$isDiscountPrice ? 'discounted_price' : 'price'};
return $product;
})->sortBy(['final_price','asc']);
In this situation, map()
Laravel Collection would be a good solution !