Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 431
Liam Potter Avatar asked Dec 28 '13 20:12

Liam Potter


People also ask

How do I merge collections in laravel?

Laravel collection merge() method merge any given array to first collection array. If the first collection is indexed array, the second collection will be added to the end of the new collection. The merge() method can accept either an array or a Collection instance.


2 Answers

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

like image 74
Altrim Avatar answered Oct 11 '22 16:10

Altrim


You don't need to loop through the $friends array, you can just use it together with whereIn like this

$posts = \Post::whereIn('poster_id', $friends)->latest()->get(); 

This replaces the empty collection creation and the foreach-loop, and gives you all your friends posts in one Collection sorted by created_at

(the latest function is a shortcut for orderBy('created_at', 'desc'))

like image 43
Arvid Avatar answered Oct 11 '22 16:10

Arvid