Count Related Models On Polymorphic Relationship
use the with method in combination with the morphTo relationship's morphWithCount method.
What is MorphTo method?
"MorphTo" is used to define the relationship from a one-to-one or one-to-many polymorphic table to whichever model or models
If you would like to eager load a morphTo relationship, as well as nested relationship counts on the various entities that may be returned by that relationship, you may use the with method in combination with the morphTo rela tionship's morphWithCount method.
In this example, let's assume Video and Post models may create ActivityFeed models. Additionally, let's assume that Video models are associated with Tag models, and Post models are associated with Comment models.
Using these model definitions and relationships, we may retrieve ActivityFeed model instances and eager load all parentable models and their respective nested relationship counts:
use Illuminate\Database\Eloquent\Relations\MorphTo;
$activities = ActivityFeed::query()
->with(['parentable' => function (MorphTo $morphTo) {
$morphTo->morphWithCount([
'App\Photo' => ['tags'],
'App\Post' => ['comments'],
]);
}])->get();
In addition, you may use the loadMorphCount method to eager load all nested relationship counts on the various entities of the polymorphic relation if the ActivityFeed models have already been retrieved:
$activities = ActivityFeed::with('parentable')
->get()
->loadMorphCount('parentable', [
'App\Video' => ['tags'],
'App\Post' => ['comments'],
]);