Guntar Guntar - 1 year ago 95
PHP Question

Insert/Update multiple records in one Eloquent Laravel query

What would be the cleanest way to process new user with roles creation and update?
I got Users and Roles tables with relationships: $this->belongsToMany(Role::class).
When I am creating a new user, in the same form I would like to assign role(s), but roles will be added into different table. And the same for when I would update the user, maybe I will add a additional role or I maybe I will need to remove some roles, In update scenario I would need to see what roles there are in the table and sync that with the form data.
Below is a function updating user and Role information. The user update works but the Role update doesn't.
What would the cleanest code to:
Create a new user with one or more roles and to update user information and sync the role information.

public function update($id, Requests\CreateUserRequest $request) {
//send email to user to reset the password

flash('Great!! User was updated', 'success');
return redirect('users');

Answer Source

To update the roles you can try as:


It will work for both update and create.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download