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

mallorca's avatar

Permissions and roles - create new user with role?

Hey artisans,

I decided to make my permissions and roles more flexible so I followed Jeff's series on ACL in Laravel and created the whole solution with roles, permissions tables and permission_role and role_user pivot tables.

When storing a user, what would be a good way to do so that it adds a role for the user and gets stored in the pivot table?

I tried with:

$user = new User($request->all());
$user->roles()->associate(2);
$user->save();

But it get the following error: Call to undefined method Illuminate\Database\Query\Builder::associate()

So I tried with attach() and update() after save, like this:

        $user->roles()->attach([
            'role_id' => 3,
            'user_id' => $user->id]);

But I get the following error: SQLSTATE[23000]: Integrity constraint violation: 1452 Cannot add or update a child row: a foreign key constraint fails

Does someone know what would be a good way to accomplish this?

0 likes
5 replies
Bloomanity's avatar

You don't need the 'user_id' when doing $user->roles()->... it's already applied.

In the first example you need to first save the user, than associate.

bobbybouwmann's avatar

You need to create the user first before you can associate the role with it, try this

$user = User::create($request->all()); // This is now a new user in the database

$user->roles()->associate(2);
mallorca's avatar
mallorca
OP
Best Answer
Level 7

Sir @CImrie 's answer in a different thread solved it:

The reason you can't use associate and can use attach then is because you have set it up as a many to many relationship rather than a one to many. I had made the assumption that a User could only have one role in my examples.

For many to many you have to create the user first, then do the attaching. No way around it I'm afraid as if you think about it, it makes sense that a pivot table needs to know both the ID of the role AND the user to make the connection. Those don't exist until both models exist in the database.

Edit:
So to do that, you should be able to do
$user = new User($request->all());
$user->save();
$user->roles()->attach(2);
´´´
bobbybouwmann's avatar

So my example does work too... Because you create the user first and then attach the role. Not sure why that wouldn't work here...

Please or to participate in this conversation.