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...