4msar's avatar
Level 2

Laravel conditional belongsToMany relationship

I have a method tenants() inside the User model, now inside this method it returns like this below which is working fine,

return $this->belongsToMany(
     Municipality::class,
     'municipality_user',
     'user_id',
     'municipality_id'
);

but I want to get all the municipality when the user is a super admin user.

$user->isSuperAdmin()

I tried with this,

if ($this->isSuperAdmin()) {
    return Municipality::all();
}

return $this->belongsToMany(
    Municipality::class,
    'municipality_user',
    'user_id',
    'municipality_id'
);

but it return this error: App\Models\User::tenants must return a relationship instance.

Should I build a custom belongsToMany class or how can I achieve that?

0 likes
1 reply
Nakov's avatar

So you are calling the method tenants() and you are trying to return municipalities it is a bit confusing.

However, Municipality::all(); returns an instance of Collection and the relationship method returns a query builder instance.

Municipality::all() also won't return the pivot model, in case you have additional columns there.

So I would suggest you move this logic in another class, either controller or action/service class whatever you use to get this data, and do the check there instead of the model. Because a relationship method under the hood uses the instance primary data to associate the corresponding data from the database, so you cannot ignore the user_id.

it will be like this:

$tenants = null;

if ($user->isSuperAdmin())
{
		$tenants = Municipality::all();
}
else
{
		$tenants = $user->tenants;
}

Please or to participate in this conversation.