I am working on creating users and assigning roles from the view and then passing them to the controller. Once I save the user, I try to register the role, but doing so gives me the following error:
Undefined property: Illuminate\Database\Eloquent\Collection::$id
What could be causing that error?
Attached the controller code:
$user = new User;
$user->card = $request->card;
$user->name = $request->name;
$user->last_name = $request->last_name;
$user->login = $request->login;
$user->password = bcrypt($request->password);
$user->save();
$role_id = $request->role_id;
$rol = Role::where('id', '=', $role_id)->get();
$user->roles()->attach($rol->id); //Aca me genera el error.
By using the method
get()
you are getting a collection, NOT a single element.The collection as such does not have the property
id
, who has it is the object or element.You can fix it in two ways:
If you know in advance that you're only going to (should) get one record, then you can use the method
first()
:If you definitely need to use
get()
for some reason, then you should reference the element you need, possibly the first one: