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...
人生最曼妙的風(fēng)景,竟是內(nèi)心的淡定與從容!
Policy
和Gate
結(jié)合起來使用就行,不復(fù)雜。Policy
的注冊在AuthServiceProvider里,如注冊一個AccountPolicy::class => Account::class
,就表示當(dāng)前User
是否有權(quán)限對Account
這個Model
Add, delete, modify and check.
In AccountPolicy
針對增刪改查操作寫上授權(quán)邏輯,如針對Delete
操作寫上$user->id === $account->user_id
authorization logic.
How to trigger this authorization logic? Can be used Model Event
觸發(fā),如在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的關(guān)系類似于Route與Controller的關(guān)系。
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');
}
}