Skip to main content

Black Friday 2025! Only until December 1st: coupon FRIDAY25 for 40% off Yearly/Lifetime membership!

Read more here

One Record from Many Records

Premium
1:52

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 of our courses? (29 h 14 min)

You also get:

54 courses
Premium tutorials
Access to repositories
Private Discord
Get Premium for $129/year or $29/month

Already a member? Login here

Comments & Discussion

V
vittalgar ✓ Link copied!

Hello sir,

Getting following error:

Filament\Support\Services\RelationshipJoiner::prepareQueryForNoConstraints(): Argument #1 ($relationship) must be of type Illuminate\Database\Eloquent\Relations\Relation, null given, called in /vendor/filament/forms/src/Components/Select.php on line 762