Skip to content
Advertisement

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

I have a table which looks like this:

Name AltName
Sam null
Ann null
null Mark
John null
null Bart
Sasha null

I want to order by both Name and AltName. If I do this:

Table::orderBy('Name')->orderBy('AltName')->get();

This will return the data in this order: Ann, John, Sam, Sasha, Bart, Mark

I don’t want it to group the data but instead merge it like this: Ann, Bart, John, Mark, Sam, Sasha

How can I achieve this using Laravel eloquent or raw SQL query?

Advertisement

Answer

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.

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