Sort collection by custom order in Eloquent

Stefan Bogdanescu

Founder & Senior Architect · 2026-06-29

Laravel Company
# Sorting Collections by Custom Order in Eloquent Dealing with data retrieval and ordering is a fundamental challenge in any application. When you use methods like `whereIn()`, you are asking the database for records matching a set of criteria. By default, most relational databases will sort these results based on the primary key, which leads to predictable but often undesired ordering. This post addresses a very common scenario: how to force Eloquent to return results in the exact sequence defined by an external array, rather than the database's natural sorting order. ## The Problem with Default Sorting As you correctly identified, when you execute: ```php $ids = [5, 6, 0, 1]; $results = Post::whereIn('id', $ids)->get(); ``` The result set will be ordered by the `id` column: `[0, 1, 5, 6]`. This is predictable but doesn't match the intended sequence of your input array `$ids`, which was `[5, 6, 0, 1]`. You need a mechanism to apply an external sort order onto the results retrieved from the database. Simply using `whereIn` and then relying on default sorting won't achieve this custom arrangement. ## The Solution: Sorting by External Array Order The easiest and most robust way to achieve a custom sort order based on an array of IDs is to leverage Laravel’s collection manipulation methods *after* fetching the data, or by using a more advanced database sorting technique if performance is critical. Since you want the resulting **collection** ordered exactly as `$ids` dictates, manipulating the resulting Eloquent Collection is often the most straightforward approach for this specific requirement. ### Method 1: Sorting the Eloquent Collection (Easiest Approach) If you have already retrieved the data via `whereIn`, you can use the input array to define a custom sort order on the resulting collection. This involves mapping the desired order back onto the items you fetched. However, if your goal is simply to ensure the final list of models appears in the sequence defined by `$ids`, you should first fetch all necessary records and then re-order them based on the index provided by `$ids`. Here is how you can achieve this conversion: ```php use App\Models\Post; $ids = [5, 6, 0, 1]; // 1. Fetch all relevant results (using whereIn) $results = Post::whereIn('id', $ids)->get(); // 2. Create a map for quick lookup of the required order // We create an index based on the desired position in the $ids array. $orderedCollection = collect(); foreach ($ids as $index => $id) { // Find the model corresponding to the ID at this specific index $model = $results->where('id', $id)->first(); if ($model) { $orderedCollection->push($model); } } // The final result is now ordered according to the $ids array, // assuming all IDs were found. $finalSortedResults = $orderedCollection->values()->all(); ``` **Explanation:** 1. We first fetch all models matching the IDs using standard Eloquent query methods (`whereIn`). 2. We iterate through your desired `$ids` array (e.g., `[5, 6, 0, 1]`). 3. For each ID in that array, we search our fetched results to find the corresponding model object. 4. We push that model object into a new collection (`$orderedCollection`). This method explicitly dictates the order based on `$ids`, regardless of how the database sorted the initial retrieval. This technique is powerful for enforcing sequence when external ordering rules are more important than database-native sorting. For complex relationships or filtering, understanding these data manipulation flows is key, much like mastering the power behind Laravel and Eloquent at resources like https://laravelcompany.com. ### Method 2: Sorting Directly in the Database (The Performance Route) If you are dealing with a very large dataset and performance is paramount, manipulating the collection in PHP after fetching everything can be inefficient. A more performant approach, if supported by your database dialect (like MySQL or PostgreSQL), is to use a custom `ORDER BY` clause that references an external sequence. Since standard SQL doesn't easily allow sorting by an arbitrary array order directly across different tables without complex subqueries, the collection manipulation method above remains the most accessible way when dealing with input arrays for ordering. However, for simple numeric