Hello everyone, I am stuck in the process of learning laravel policy. I know the difference between laravel policy and middleware, but I still don’t know how to apply the policy. Can the moderator provide a complete small program? Thank you very much.
This is an image answer about policy that I found on stackoverflow, http://stackoverflow.com/ques...
Then this is the code I stored on github when I was practicing. If anyone is willing to add the policy function to my code, I would be very grateful. You can use the policy for any function, as long as you add the policy to it
https://github.com/GoogleYY/s...
PHP中文网2017-05-16 16:50:50
Policy
和Gate
结合起来使用就行,不复杂。Policy
的注册在AuthServiceProvider里,如注册一个AccountPolicy::class => Account::class
,就表示当前User
是否有权限对Account
这个Model
Add, delete, modify and check.
In AccountPolicy
针对增删改查操作写上授权逻辑,如针对Delete
操作写上$user->id === $account->user_id
authorization logic.
How to trigger this authorization logic? Can be used Model Event
触发,如在EventServiceProvider::boot()
ri
Event::listen('eloquent.deleting: *', function (Model $model) {
if(Gate::denies('delete', $object)) {
throw new ForbiddenHttpException("You donot have permission delete {get_class($model)}.");
}
})
Gate与Policy的关系类似于Route与Controller的关系。
巴扎黑2017-05-16 16:50:50
After the email help from foreign stackoverflow master Amit Gupta, it is now solved.
Step 1: First register the policy, and establish the connection relationship between the Model and the policy in AuthServiceProvider.php under the Providers folder, as follows:
protected $policies = [
\App\Models\Role::class => \App\Policies\RolePolicy::class,
\App\Models\Permission::class => \App\Policies\PermissionPolicy::class,
];
The second step is to create a new PermissionPolicy through the php artisan make:policy command, and write the relevant permission control into the two policies through functions, as shown below:
class PermissionPolicy
{
public function before($user, $ability) {
if ($user->hasRole('admin')) {
return true;
}
}
public function create(\App\Models\User $user, \App\Models\Permission $permission)
{
return $user->hasPermission('permission.create');
}
}
The last step is to use the related functions set by this policy in the controller, as follows:
class PermissionController extends Controller {
public function create() {
$this->authorize('create', new \App\Models\Permission);
return view('permissions.create');
}
}