2
votes

During assigning roles in laravel by using entrust i am getting error

Method Illuminate\Database\Eloquent\Collection::getKey does not exist. My code is :


    $record = new User();
    $data = $request->all();
    $record->fill($data);
    $record->save();
    $roles = [1, 3]
    $role = Role::whereIn('id', $roles)->get();
    $record->attachRole($role);

1
you can attact role to user what is record here.? - Kamlesh Paul
You are fetching roles from the database with the id 1 and 3 but you are not doing anything with them? What is $record and what is $role? - Remul
@Remul updated code - Ranjeet
$role is currently a collection of roles, did you try attaching only one role e.g.: $record->attachRole(1), it is unclear from the documentation if you can pass multiple roles to attachRole - Remul
one role is working, - Ranjeet

1 Answers

1
votes

You are using attachRole which is used to attach a single role to a user.

You want to use attachRoles to attach multiple roles to a user.


So in your case:

$record = new User();
$record->fill($request->all());
$record->save();

$roles = Role::whereIn('id', [1, 3])->get();
$record->attachRoles($roles);