Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

daniel21gt's avatar

problem -> roles () -> attach in laravel 5.5

The last line of code is not executed

$user->roles()->attach(Role::where('name', 'user')->first()); return $user;

https://paste.laravel.io/ea20d207-ef15-49d8-8db8-98f3786ea939

I should add the assigned role to a table but it does not, now if I do this same thing in seeder if it works, like this, why?

https://paste.laravel.io/6ae2a66a-4bd1-4a41-b496-63c7f6a41cf7

0 likes
2 replies
realrandyallen's avatar
Level 44

The $user variable doesn't exist and you're returning out of the function right away so that code is never executed, try this:

$user = User::create([
    'name' => $data['name'],
    'email' => $data['email'],
    'password' => bcrypt($data['password']),
]);
 
$user->roles()->attach(Role::where('name', 'user')->first());

return $user; 

Please or to participate in this conversation.