You forgot the parentheses on roles.
$newUser->roles()->attach($role);
Without the parenthesis you are lazy loading the collection of roles. You need the relationship.
Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.
Hello,
I'm still a beginner at laravel. I'm trying to auto assign roles to new user in different controllers. In the EmployeeController :
public function store(StoreEmployeeRequest $request)
{
$employee = Employee::create($request->all());
$user = User::create([
'name' => $request->full_name,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->professional_email,
]);
$role = Role::where('title', 'Staff')->first();
$user->roles()->attach($role);
return redirect()->route('employees.index');
}
In the StudentController :
public function store(StoreStudentRequest $request)
{
$student = Student::create($request->all());
$user = User::create([
'name' => $request->full_name,
'first_name' => $request->first_name,
'last_name' => $request->last_name,
'email' => $request->school_email,
]);
$role = Role::where('title', 'Student')->first();
$user->roles()->attach($role);
return redirect()->route('students.index');
}
For both Employee and Student it's working, but now I'm trying so that any user that self registered will be registered as a Guardian.
I tried this code on the RegisterController :
protected function create(array $data)
{
$newUser = User::create([
'first_name' => $data['first_name'],
'last_name' => $data['last_name'],
'email' => $data['email'],
'password' => Hash::make($data['password']),
]);
$role = Role::where('title', 'Guardian')->first();
$newUser->roles->attach($role);
return $newUser;
}
But it's not working : Method Illuminate\Database\Eloquent\Collection::attach does not exist. What should I do? Please help.
You forgot the parentheses on roles.
$newUser->roles()->attach($role);
Without the parenthesis you are lazy loading the collection of roles. You need the relationship.
Please or to participate in this conversation.