Looking for a complete code about the actual application of laravel policy
黄舟
黄舟 2017-05-16 16:48:50
0
2
477

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...

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(2)
洪涛

PolicyGate结合起来使用就行,不复杂。Policy的注册在AuthServiceProvider里,如注册一个AccountPolicy::class => Account::class,就表示当前User是否有权限对Account这个ModelAdd, delete, modify and check.

In AccountPolicy针对增删改查操作写上授权逻辑,如针对Delete操作写上$user->id === $account->user_idauthorization 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的关系。

巴扎黑

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');
    }
}
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template