简体   繁体   中英

Laravel Policies with Many-to-Many relationship

Role and Permission are two models and since they have many-to-many relationship, I have an intermediate table called permission_role table. But this doesn't have a Model. I am trying to attach a Permission to a Role . But $this->authorize('create', RolePermission::class); always fails with error "This action is unauthorized."

Route :

Route::post('/rolepermissions/{role}/addpermission', 'RolePermissionController@store')
       ->name('rolepermission.store');

RolePermissionController :

public function store(StoreRolePermission $request, Role $role)

{
    $this->authorize('create', RolePermission::class);

    ...
}

RolePermissionPolicy :

public function create(User $user)
{
    if (($user->usertype == 'ADMIN') || ($user->usertype == 'SUPERADMIN'))
    {
        return true;
    }
    else
    {
        return false;
    }
}

Is it because the intermediate table does not have an associated Model?

I had a similar scenario, and I'm doing:

Auth:user()->can('create', RolePermission::class); , instead of authorize.

I think (have not tested) you can also do:

$this->authorize('create', [RolePermission::class, Auth::user()]) . The second argument in the array will get passed as the only param in your policy.

I'm very new to Laravel, I got some help to solve a similar issue, hope this works for you.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM