Courses

Laravel 12 Eloquent: Expert Level

One Record from Many Records

You're reading a FREE PREVIEW of a PREMIUM course.
Summary of this lesson:
- Using ofMany() for relationship filtering
- Implementing latest/oldest relationship queries
- Managing complex relationship conditions
- Understanding single record relationship retrieval

Video Version of the Lesson

[Only for premium members]

Link to the repository

[Only for premium members]

As a final lesson in this section of the course about advanced relationships, I want to show you a method ofMany().


The situation: you have a has-many relationship (user has many projects) but you need to query only the latest project.

Only one, not all of them, just the latest. Before Laravel 8, when ofMany() was introduced, people did that with various hacky workarounds. Now, you can define a hasOne relationship and provide latestOfMany().

use Illuminate\Database\Eloquent\Relations\HasOne;
 
class User extends Authenticatable
{
// ...
 
public function projects(): HasMany
{
return $this->hasMany(Project::class);
}
 
public function latestProject(): HasOne
{
return $this->hasOne(Project::class)->latestOfMany();
}
}

In the same way, you can get the...

The full lesson is only for Premium Members.
Want to access all 38 video+text lessons of this course? (1 h 34 min)

You also get:

  • 78 courses
  • Premium tutorials
  • Access to repositories
  • Private Discord