Look closely at your code, the attachRole
method expects an object, not a number.
public function attachRole() {
if(!$this->hasRole($role->name)) {
$this->roles()->attach($role);
}
}
The object must contain a property name
, see line 51 of the code (according to the image you inserted in the peg).
So, the code $user->attachRole(12);
causes the following error to be triggered:
Trying to get property 'name' of non-object
Translating, the code is trying to get the name
property of an element that is not an object.
The $user->roles()
method returns an object that provides the attach
method, so it works:
$user->roles()->attach(12);
There is certainly some validation within the attach
method that checks whether the value entered is an object, so no error is triggered, but this is only by analyzing the method code.