Courses

Laravel 12 Eloquent: Expert Level

One Record from Many Records

Summary of this lesson:
- Using ofMany() for relationship filtering
- Implementing latest/oldest relationship queries
- Managing complex relationship conditions
- Understanding single record relationship retrieval

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 28 lessons of this course? (71 min read)

You also get:

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