How to configure spatie/laravel-permissions - only edit/update/delete owners posts
Is there a way to configure Spatie/Laravel-Permissions to permit registered users to only modify their own posts. I've got the roles and permissions package installed and partially configured. When I use the @can("edit-post") , it allows all posts to be modified (caveat: This is fine for admins and moderators). Do I need to add Gates to the AuthServiceProvider to specifically specify what roles can access when attempting to edit? For example, the code below only considers that the user_id's match the owner id:
class PostPolicy
{
/**
* Determine if the given post can be updated by the user.
*/
public function update(User $user, Post $post): bool
{
return $user->id === $post->user_id;
}
}
In blade
@can('update', $post)
spatie/laravel-permissions is for all functionalities permissions, not model specified.
I will just add the following example to make things clearer for future users.
We can use Spatie permissions inside the policy to make it more clearer, like:
class PostPolicy
{
public function update(User $user, Post $post): bool
{
// Checking it the user can edit all posts (Spatie part) or the post belong to user.
return $user->can('edit posts') || $user->id === $post->user_id;
}
}
@MohamedTammam@snapey Thank you both for your advice on this. Much appreciated. I was under the impression Spatie/Laravel-Permissions was supposed to handle the whole thing. :)
@MohamedTammam Does this affect the @can functionality in the blade template or just the backend? I created an UpdatePolicy with the code you suggested and tried both
@jmacdiarmid update-questions won't use your model policy since it is being used just to check permission to perform a specific function and not related to a specific model, you would need it to be update-question and pass in the specific model you want to check.