Let's say that I have three users in my system Sam
, John
and Sarah
. All three have a role of editor
which gives them permission to create article
, edit article
, publish article
and delete article
. Now for some reason, I don't want Sam
to have permission to delete article
but still have the role of editor
.
How can I achieve this in Laravel with this spatie/laravel-permission package? (Assume that I may have to do such operation on a somewhat regular basis and there are after some time I may assign back delete article
again the Sam
. And there are way too many permissions in any role, so i can't do it manually.)
You can create custom policies.
In the Policy you set an exception for your user or group of users.
To create and save your policy.( https://laravel.com/docs/6.x/authorization#creating-policies )
Example Policy
<?php
namespace App\Policies;
use App\User;
use App\Article;
use Illuminate\Auth\Access\HandlesAuthorization;
class ArticlePolicy
{
use HandlesAuthorization;
/**
* Determine whether the user can delete the article.
*
* @param \App\User $user
* @param \App\Post $post
* @return mixed
*/
public function delete(User $user, Article $article)
{
// retrieve the user as you wish.
// I just did a check with his name but it is preferable to have a more
// advanced identification.
if ($user->name = 'SAM')) {
return false;
}
if ($user->can('delete article')) {
return true;
}
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.