0

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?

1 Answer 1

1
public function tenants(): BelongsToMany
{
    $relation = $this->belongsToMany(
        Municipality::class,
        'municipality_user',
        'user_id',
        'municipality_id'
    );

    if ($this->isSuperAdmin()) {
        // For super admins, return a new query for all municipalities
        return Municipality::query();
    }

    return $relation;
}
Sign up to request clarification or add additional context in comments.

1 Comment

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.