Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

eddy1992's avatar

having condition in a Laravel eloquent query.

Hi I have an eloquent query and the table I am querying contains a column named active. So active could be 1 or 0. Now I am querying all the records from the table, that means I have all the records which may have active = 1 or active = 0. Now what I want to do is that I want to show or get the active = 1 records first then the those records which have active = 0.

//now Imagine we get all the records from this query so the $allRecords variable has 
//all the records which are active and not active.
$allRecords = Product::where('city', 'New York')->get();

//Now I want to sequence or reorder the collection where I want to show the active=1 first then active=0.

please assist.

0 likes
5 replies
tykus's avatar
tykus
Best Answer
Level 104

The speediest way to order the records is in the database query:

$allRecords = Product::where('city', 'New York')->orderBy('active', 'desc')->get();
RamjithAp's avatar

First 1 and then 0

$allRecords = Product::where('city', 'New York')->orderBy('active','DESC')->get();

First 0 and then 1

$allRecords = Product::where('city', 'New York')->orderBy('active','ASC')->get();
eddy1992's avatar

@tykus Thank you so much for your reply but I wanted to know whether I could user sortBy() to achieve this ?

tykus's avatar

You can use sortBy(), but why would you? The SQL query would be relatively trivial compared with the expense of sorting a large Collection in PHP.

Please or to participate in this conversation.