vincent15000's avatar

How to eager load a count from a morph to many relationship ?

Hello,

I have checked the documentation.

https://laravel.com/docs/11.x/eloquent-relationships#morph-to-deferred-count-loading

And tried to apply like this.

$event->load(['image', 'type', 'location', 'activities' => function ($query) {
    $query->loadMorphCount('registrationable', [Activity::class => 'registrations']);
}]);

But I get this error.

Call to undefined method Illuminate\Database\Eloquent\Relations\HasMany::loadMorphCount()

Activity model

public function registrations()
{
    return $this->morphToMany(Registration::class, 'registrationable');
}

Registration model

public function activities()
{
    return $this->morphedByMany(Activity::class, 'registrationable');
}

Can you help me understand what is wrong ?

Thanks for your help.

V

0 likes
1 reply
vincent15000's avatar
vincent15000
OP
Best Answer
Level 63

Here was my error : it was not a many to many polymorphic relationship, but just a one to many.

public function registrations()
{
    return $this->morphMany(Registration::class, 'registrationable');
}
public function activity()
{
    return $this->morphOne(Activity::class, 'registrationable');
}

Please or to participate in this conversation.