Search code examples
phpcollectionslaravellaravel-4eloquent

Sort Eloquent Collection by created_at


I have a table named 'posts' with the columns: 'post_id int primary increments', 'poster_id int' and 'status text' as well as an array named friends with the columns: 'user_id int primary' and 'friend_ids text'.

I need to grab all the IDs in the friends text column which is easy enough using:

$friends = explode(',', \Friend::where('user_id', \Sentry::getUser()->id)->first()->friend_ids);

Where the data in the text column would look like '1,2,3,' etc.

Then I create an Eloquent Collection object which is also easily done via:

$posts = new \Illuminate\Database\Eloquent\Collection();

But the problem is I can't figure out how to populate the collection and sort its contents by the Post object's 'created_at' column.

This is what I have at the moment:

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

I can't figure out if this code would work or not for sorting the entire collection of posts by the 'created_at' column. I would also need to be able to paginate the entire collection easily.

What is the recommended way of sorting the collection?


Solution

  • If you want to sort a collection you can use the sortBy method by given key

    $sorted = $posts->sortBy('created_at');
    

    Also you can apply a callback function on the collection

    $sorted = $posts->sortBy(function($post)
    {
      return $post->created_at;
    });
    

    Hope this helps. For more information on collections you can read the docs