Sort Eloquent Collection by created_at Sort Eloquent Collection by created_at laravel laravel

Sort Eloquent Collection by created_at


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


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'))


Sorting with pagination can be implemented like this in Laravel 8:

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