8 months ago

Eager load pivot model relations

Posted 8 months ago by dentintheuniverse

I have boards, users and roles. Users are members of boards but with specific roles. So here is the basic setup:

class User extends Model {}

class Role extends Model {}

class Board extends Model
    public function members(): BelongsToMany
        return $this->belongsToMany(\App\Users::class)

class BoardMembership extends Pivot
    public function role(): BelongsTo
        return $this->belongsTo(\App\Role::class);

The following statement:

$members = \App\Board::find(1)->members;

Gives us this:

    \App\User {
        id: 1,
        membership: \App\BoardMembership {
            board_id: 1,
            user_id: 1,
            role_id: 1

It's all ok until here. What I need to do is to eager load the role relation on BoardMembership pivot model and running this:


gives the following error:

Illuminate/Database/Eloquent/RelationNotFoundException with message 'Call to undefined relationship [membership] on model [App/User].'

Laravel is trying to eager load the relationship on the User model, not the pivot model. I've tried every possible combination as the relationship name (membership.role, pivot.role, user.pivot.board, user.membership.role, etc.) and no luck.

Do you have any ideas about how to eager load pivot model relations?

Please sign in or create an account to participate in this conversation.