Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

devionti's avatar

policy for BelongsToMany field

In the hasMany field the policies create, update if disabled then the field will disable it making it view only which is what I want for the BelongsToMany

BelongsToMany::make('Something', 'something', \App\Nova\Something::class),
hasMany::make('Something', 'something', \App\Nova\Something::class),

Its just for the belongsToMany Field can't seem to make it view only for some users. The policies does nothing for it. Also in nova documentation there is the canSee authorisation which is not what I want.

https://nova.laravel.com/docs/3.0/resources/authorization.html#relationships

What is the best way to make the BelongsToMany Field a View only for users.

0 likes
5 replies
bobbybouwmann's avatar
Level 88

BelongsToMany is a many-to-many relationship. This basically means it's only connected by a pivot table, so each model is its own identity. Because of that, you need to enable it on the model itself.

So in your case, if you want to be able to see the model from you need to set the policy for that model

class SomethingPolicy
{
    public function viewAny()
    {
        return true;
    }

    public function view()
    {
        return true;
    }
}

Because the view of Something is true, you can always click on it from your other many-to-many model.

1 like
devionti's avatar

idk if I can reopen instead of saying it is solved but it didn't work. I tried multiple methods including attach{model} didn't work. I still can attach.

    public function attachAnyRole(User $user, Role $role)
    {
        return false;
    }
        MorphToMany::make('Roles', 'roles', \Vyuldashev\NovaPermission\Role::class),
TheAnswerIsAlwaysMaybe's avatar

Note that it's based on the model name, not the relationship name. I was stuck on that for quite some time. So it's: attach{Model} (like the docs say) for a single model. And attachAny{Model} for attaching any.

TheAnswerIsAlwaysMaybe's avatar

Also note... I just read my own reply from 4 months ago, and again I was frustrated like crazy. The Str::singular() method which is used under the hood does not ALWAYS correctly use the right singular form of your model name. My model name ends with "Analysis" of which it thinks the singular form is "Analysi" which would make your policy name "attachAnyAnalysi".

Please or to participate in this conversation.