Search code examples
laravelcollectionseloquent

How to re-order an Eloquent collection?


I've got a collection of records retrieved via a relationship, and I'd like to order them by the created_at field. Is this possible in Eloquent?

Here is how I am retrieving the collection:

$skills = $employee->skills;

I'd like to order this $skills collection by their creation. I've tried $skills->orderBy('created_at', 'desc'); but the Collection class does not have an orderBy method.

I guess this problem is very simple and I'm missing something..


Solution

  • The reason this is failing is that orderBy is a query method not a collection method.

    If you used $skills = $employee->skills()->orderBy('created_at', 'desc')->get();, this would query the skills in the order you want.

    Alternatively, if you already had a collection that you wanted to re-order, you could use the sortBy or sortByDesc methods.