php – Laravel Nova – How to hide 'Create' button from HasMany field?-ThrowExceptions

Exception or error:

I’ve User model which has HasMany relation with Post model. When I include a field for HasMany in User resource of Nova, I see there is Create post button. How do I remove/hide that button?

How to solve:

You could achieve this with Policies.

According to the documentation:

If a policy exists but is missing a method for a particular action, the user will not be allowed to perform that action. So, if you have defined a policy, don’t forget to define all of its relevant authorization methods.

So in your case, if you want to hide the button completely, just create a policy for your resource (PostPolicy) and don’t implement the create method.

Answer:

You need to 2 things here.

  1. In your Post resource

    public static function authorizable()
    {
    return true;
    }

  2. Now create policy for Post and return true for all methods except create, for create return false and in AuthServiceProvider.php

put

protected $policies = [
    Post::class => PostPolicy::class,
];

And you are done.

Answer:

In case someone is still looking for the solution, you can authorise attaching/detaching resources in your policies:

https://nova.laravel.com/docs/2.0/resources/authorization.html#authorizing-attaching-detaching

So in this case, you have a UserPolicy to which you add a function:

attachPost(User $user, User $model, Post $post)
{
    return false;
}

The $user variable is the user that is signed in, the $model variable is the user page that is viewed.

Leave a Reply

Your email address will not be published. Required fields are marked *