Relation that will get the newest (or oldest) item

New in Laravel 8.42: In an Eloquent model can define a relation that will get the newest (or oldest) item of another relation.

1public function historyItems(): HasMany
2{
3 return $this
4 ->hasMany(ApplicationHealthCheckHistoryItem::class)
5 ->orderByDesc('created_at');
6}
7 
8public function latestHistoryItem(): HasOne
9{
10 return $this
11 ->hasOne(ApplicationHealthCheckHistoryItem::class)
12 ->latestOfMany();
13}

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 22 courses (477 lessons, total 38 h 20 min)
  • 2 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord