Laravel: Sort by Relation

Imagine you have rows of different categories. This means each row belongs to a category and a category has many rows.

Imagine you want to sort your categories by the latest row.


category_id name
1 the right
2 this is
3 order
id category_id created_at
1 1 2020-01-01 12:00
1 1 2020-01-01 13:00
2 2 2020-01-01 13:30

We would like to get the category sorted as

  • this is
  • the right
  • order

How to

A category hasMany rows, but only one latest row. Thats why we need to create a hasOne relation:

public function latestRow()
    return $this->hasOne(\App\Row)->latest();

Now you can get all categories ordered by latest row like this:


Leave a comment

Your email address will not be published. Required fields are marked *