Sort Eloquent Collection by created_at

Sort Eloquent Collection by created_at

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Sort Eloquent Collection by created_at

When working with Laravel, there is a distinct difference between querying a database table and manipulating an in-memory collection. The core issue in your scenario stems from how orderBy functions within each context. When you query the database directly using Post::where(...)->orderBy('created_at', 'desc')->get(), the sorting logic executes on the SQL server before any data is returned to PHP. However, once you load those models into an Illuminate\Database\Eloquent\Collection and iterate through them in a loop, the data is already fully hydrated in memory. The database query has finished, and the results are now just PHP objects.

Attempting to sort this aggregated collection afterwards requires sorting the entire array of models in memory rather than relying on SQL. While Laravel provides a sortBy() method on collections (inherited from Illuminate\Support\Collection), applying it directly to your current approach introduces specific performance and architectural pitfalls that need addressing.

The In-Memory Sorting Challenge

Your current implementation fetches posts for every friend separately:

foreach ($friends as $id) {
    $posts_ = \Post::where('poster_id', $id)->getQuery()
        ->orderBy('created_at', 'desc')
        ->get();
    foreach($posts_ as $post) {
        $posts->add($post);
    }
}

This code does technically add the items to the collection, but it creates an unsorted list. The individual queries inside the loop are ordered by created_at in descending order for that specific friend's posts only. They are not globally sorted against one another. When you finish the loop, $posts contains all the records, but they are merely concatenated in the order they were fetched (Friend A's posts, then Friend B's posts, etc.).

To sort this entire collection by created_at, you must invoke the collection's sorting method after the loop completes:

$sortedPosts = $posts->sortByDesc(function ($post) {
    return $post->created_at;
});

This approach works perfectly for small to medium-sized datasets. However, it forces Laravel to load every single post from the database into memory before performing any sorting logic in PHP. This is often referred to as an N+1 query problem combined with an inefficient data transfer strategy. If you have thousands of friends and many posts per friend, you will hit memory limits quickly because you are loading everything at once.

A More Efficient Approach: Single Query Sorting

The recommended pattern in Laravel is to avoid looping over relationships to aggregate data if a single query can handle the logic. Instead of fetching posts individually for each user, construct a single query that joins the necessary tables or uses subqueries to filter by the friends list.

Once you have the filtered set of posts from a single database hit, apply the sort before pagination:

// Construct the raw IDs safely using array_map or similar if needed
$friendIds = explode(',', \Friend::where('user_id', \Sentry::getUser()->id)->first()->friend_ids);

// Filter the query to only include posts by these users
$posts = Post::whereIn('poster_id', $friendIds)
    ->orderBy('created_at', 'desc')
    ->get(); // Sort happens in SQL here, then we get a sorted collection

// Now paginate easily
$pagePosts = $posts->chunk(10); 

Wait, chunk is for processing, not pagination for display. For standard pagination, you would typically use paginate(). However, paginate() relies on the database driver to split the result set. If your sorting logic is complex or if you need custom ordering that doesn't map cleanly to a single SQL ORDER BY clause, get() followed by paginate() (which converts to an array of pages) might be necessary.

Actually, standard pagination (->paginate()) works best when the query returns a sorted result set that the database can handle efficiently. If you use get() to load everything into memory and then try to paginate using Paginator::make($posts), you are effectively bypassing SQL pagination. This is fine for small datasets but defeats the purpose of efficiency with large data volumes.

Trade-offs and Best Practices

The primary trade-off here is between Data Transfer and Memory Usage.

  1. In-Memory Sorting: Using sortBy() on a collection loaded via ->get() ensures you have full control over the order, but it requires loading the entire dataset into RAM. This is acceptable if the total row count is manageable (e.g., under 5,000 rows).
  2. Database Sorting: Letting the database handle ORDER BY keeps memory usage low because only a subset of data needs to be transferred for pagination. However, this requires that your SQL query can express the sorting logic directly.

If you must stick with your current architecture (looping through friends), ensure you sort the collection after the loop finishes:

foreach ($friends as $id) {
    // Fetch and add without relying on internal ordering of the batch
    $posts->addMany(\Post::where('poster_id', $id)->get()); 
}

// Sort the entire collection in memory by created_at
$posts = $posts->sortByDesc(function ($post) {
    return $post->created_at;
});

// Now you can slice for pagination manually or convert to a paginator
$perPage = 15;
$page = 1; // Assuming user provided page number
$start = ($page - 1) * $perPage;
$end = min($start + $perPage, count($posts));
$currentPosts = array_slice($posts->toArray(), $start, $end);

This manual slicing is a last resort. Ideally, you should refactor to use whereIn to fetch the relevant posts in one go and let the database sort them before they ever enter your PHP application. This adheres to the "N+1" best practice of avoiding unnecessary loops for data aggregation.

Our network