Search code examples
phpjsonlaravelpermissionsentrust

Add multiple permissions to one role entrust Role-based Permissions for Laravel 5



I just add entrust to Laravel project, i can create role, create permission , attachPermission, assignRole.

Now i want to attach multiple permissions to one Role ,for example i add this permissions [create-user,edit-user,remove-user,update-user] to superAdmin Role.

public function attachPermission(Request $request){
        $role = Role::where('name', '=', $request->input('role'))->first();
        $permission = Permission::where('name', '=', $request->input('name'))->first();
        foreach ($permission as $pers){
            $role->attachPermissions($pers);
        }
            return response()->json("done");
    }

This code take last just permission, this is a backend i test with Postman.
So what's the best why to do it ? and thanks for help .


Solution

  • First retrieve the permissions you wish to assign to the role:

    $permissionNames = ['name1', 'name2', 'name3'];
    
    $permissions = Permission::whereIn('name', $permissionNames)->get();
    

    and then you can pass the $permissions collection to the attachPermissions() method which accepts an array of Eloquent models:

    $role->attachPermissions($permissions);