How to Use Order by For Multiple Columns in Laravel 4

How to Use Order By for Multiple Columns in Laravel 4?

Simply invoke orderBy() as many times as you need it. For instance:

User::orderBy('name', 'DESC')
->orderBy('email', 'ASC')
->get();

Produces the following query:

SELECT * FROM `users` ORDER BY `name` DESC, `email` ASC

Order by query using 2 columns using laravel

You could use a case expression for you criteria

->orderByRaw("CASE WHEN role ='lawyer' THEN 1 ELSE 0 END DESC")
->orderBy( 'login_status', 'DESC' );

Plain sql would be like

select *
from demo
order by CASE WHEN role ='lawyer' THEN 1 ELSE 0 END DESC, login_status DESC

Demo

Or you can make your order clause even shorter like

order by role ='lawyer' DESC, login_status DESC

Demo

How to order by multiple columns not creating different groups using Laravel eloquent

What you probably want here is a COALESCE of some sort, if you want to do it in SQL.

This should do the trick;

Table::orderByRaw('COALESCE(Name,AltName)')->get();

It shouldn't matter which way around you put Name and AltName given that your data shows one is always NULL if the other value is present.

how to apply sortBy for two columns. in laravel eloquent

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

Laravel 5.1 - Order by two columns not working as intended

I think you have to use the quarter_year first, like this:

$last_figures = QuarterData::where('company_id', '=', $company->id)
->orderBy('quarter_year')->orderBy('quarter_number')->get();

order by 2 conditions on query eloquent

I think you need to try this

$timelineFeed = SoccerMatchTimeline::where('soccer_match_id',$id)
->orderBy('minute', 'DESC')
->orderBy('created_at', 'desc')->get();

Since you have mentioned, that you need to sort first from minute then from created_at



Related Topics



Leave a reply



Submit