Search code examples
laravellaravel-9laravel-permission

set permission to role spatie/laravel-permission


I'm trying to use this library and set permission to my users. I'm reading documentation and I created my roles. I set my array in input with name.

@foreach ($allPermission as $permission)
                    <div class="col-md-2">
                      <label class="form-check-label mr-4" for="{{ $permission->id }}">{{ $permission->name }}</label>
                      <input class="form-check-input" name="permission[]" type="checkbox" id="{{ $permission->id }}" value="{{ $permission->name }}">
                    </div>
                  @endforeach

In my controller, I received this:

Array ( [0] => show [1] => create [2] => destroy )

I'm trying to set this permissions with this:

$user = User::where("id", $id)->update([
                                    'name'      => $request->get('name'),
                                    'email'     => $request->get('email'),
                                    'password'  => \Hash::make($request->get('password')),
                                ]);
            
            // update permissions to user
            $user->givePermissionTo($request->get('permission'));

this returns...

Call to a member function givePermissionTo() on int

I'm trying to set permissions with id and with name and getting same error.


Solution

  • $user = User::where("id", $id)->update([
                                        'name'      => $request->get('name'),
                                        'email'     => $request->get('email'),
                                        'password'  => \Hash::make($request->get('password')),
                                    ]);
    

    return $user is count records was updated ($user of you is not a collection)

    you can use :

    $user = User::find($id);
    

    then

    $user->givePermissionTo($request->get('permission'));