'Eager loading polymorphic relations in Laravel Eloquent
I am using rappasoft/laravel-authentication-log with my User model. It exposes the following polymorphic relation to the User model:
public function authentications()
{
return $this->morphMany(AuthenticationLog::class, 'authenticatable')->latest('login_at');
}
Now, if I run $user->authentications->some_property ($user is from User::get() collection), it emits N+1 queries. How do I eager load this relationship?
I've tried User::with('authentications')->get() but it doesn't seem to be working. I'm still getting N+1 queries.
Solution 1:[1]
Ok, It seems the eager loading is working as-is. I was using the $user->getLastLoginAt() method which loads the relationship explicitly:
public function lastLoginAt()
{
return optional($this->authentications()->first())->login_at;
}
I've changed the code to optional($this->authentications->first())->login_at and I'm no longer generatig N+1 queries
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | masroore |
