Eager load pivot model relations

Posted 5 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)
            ->withPivot(['role_id'])
            ->using(BoardMembership::class)
            ->as('membership');
    }
}

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:

\App\Board::find(1)->members()->with('membership.board')->get();

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.