Performance: Polymorphic relationships
This affects database query performance and page load speed by influencing how many queries and joins are executed.
Post::with('comments')->get();
Post::all()->each(fn($post) => $post->comments);
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Lazy loading polymorphic relations | Minimal DOM impact | Minimal | Minimal | [X] Bad - causes multiple queries delaying content |
| Eager loading polymorphic relations | Minimal DOM impact | Minimal | Minimal | [OK] Good - reduces queries and speeds data availability |
morphTo() to define the polymorphic inverse relationship.morphMany(), but the related model uses morphTo().$comment->commentable->name output?class Comment extends Model {
public function commentable() {
return $this->morphTo();
}
}
$comment = Comment::find(1);name = 'Laravel Tips'.commentable() method returns the related model instance, here a Post.name on the Post model returns 'Laravel Tips'.class Image extends Model {
public function imageable() {
return $this->morphMany();
}
}morphTo() for polymorphic inverse.morphMany() is for owning models, not related models.Post and Video models can have many Comment models. Which of the following is the correct way to define the relationship in the Post model?morphMany().morphMany() requires the related model class and the polymorphic name 'commentable'.Pass the test and this pattern moves unknown