Getting error Method Illuminate\Database\Eloquent\Collection::getKey does not exist. in laravel, how to fix it?

6.7k views Asked by At

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

There are 1 answers

0
Remul On

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);