Skip to content

[12.x] Add inOrderOf() method to query builder#59162

Merged
taylorotwell merged 1 commit intolaravel:12.xfrom
faytekin:add-in-order-of
Mar 12, 2026
Merged

[12.x] Add inOrderOf() method to query builder#59162
taylorotwell merged 1 commit intolaravel:12.xfrom
faytekin:add-in-order-of

Conversation

@faytekin
Copy link
Contributor

Adds an inOrderOf() method to the query builder for ordering results by a given sequence of values.
Sorting by a specific value order is a common need (e.g. status-based sorting in e-commerce, priority-based sorting in task management). Today this requires orderByRaw() with a manual CASE expression, which is verbose and error-prone.

$orders = DB::table('orders')
    ->inOrderOf('status', ['pending', 'processing', 'shipped', 'delivered', 'cancelled'])
    ->get();

The method compiles to a parameterized CASE clause, places unmatched values after the given sequence, and chains naturally with existing orderBy() calls.

Tests cover the query builder and MySQL, PostgreSQL, and SQL Server grammars.

No breaking changes.

@ilhanaydinli
Copy link

Nice addition 👏
I usually had to use orderByRaw with CASE WHEN for this. inOrderOf() makes it much cleaner. Thanks for this.

@Jubstaaa
Copy link

+1

@metintaka
Copy link

my orderByRaw('FIELD(...)') snippets are finally getting a proper retirement

@dilaramelisayaman
Copy link

love additions like this. anything that keeps me out of raw SQL is a win.

@Rizky92
Copy link
Contributor

Rizky92 commented Mar 11, 2026

Why not use FIELD(column, ?, ?, ?)?

@epicentre
Copy link

Looks good to me. The $values parameter should also support enums.

@faytekin
Copy link
Contributor Author

faytekin commented Mar 12, 2026

Why not use FIELD(column, ?, ?, ?)?

FIELD() only works on MySQL. CASE WHEN works on all databases and performance is the same. Rails also tried FIELD() first and switched to CASE WHEN for this reason (rails/rails#45670)

@faytekin
Copy link
Contributor Author

Looks good to me. The $values parameter should also support enums.

It already does. cleanBindings() handles BackedEnum values automatically, so inOrderOf('status', [Status::Active, Status::Pending]) works out of the box.

@taylorotwell taylorotwell merged commit 8365873 into laravel:12.x Mar 12, 2026
72 checks passed
@faytekin faytekin deleted the add-in-order-of branch March 12, 2026 18:12
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

8 participants