Laravel - Relationships - Counting Related Models On Morph To Relationships
If you would like to eager load a "morph to" relationship, as well as related model counts for the various entities that may be returned by that relationship, you may utilize the with
method in combination with the morphTo
relationship's morphWithCount
method.
In this example, let's assume that Photo
and Post
models may create ActivityFeed
models. We will assume the ActivityFeed
model defines a "morph to" relationship named parentable
that allows us to retrieve the parent Photo
or Post
model for a given ActivityFeed
instance. Additionally, let's assume that Photo
models "have many" Tag
models and Post
models "have many" Comment
models.
Now, let's imagine we want to retrieve ActivityFeed
instances and eager load the parentable
parent models for each ActivityFeed
instance. In addition, we want to retrieve the number of tags that are associated with each parent photo and the number of comments that are associated with each parent post:
use Illuminate\Database\Eloquent\Relations\MorphTo;
$activities = ActivityFeed::with([
'parentable' => function (MorphTo $morphTo) {
$morphTo->morphWithCount([
Photo::class => ['tags'],
Post::class => ['comments'],
]);
}])->get();