Guntar Guntar - 1 month ago 17
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) {
$user=User::findOrFail($id);
$user->name=$request->name;
$user->email=$request->email;
if($request->resetPassword)
{
$user->password=null;
//send email to user to reset the password
}
$user->save();
$roles=Role::sync($request->roles);
$roles->user()->update($user->id);

//$user->update($request->all());
flash('Great!! User was updated', 'success');
return redirect('users');
}

Answer

To update the roles you can try as:

$user->save();
$user->roles()->sync($request->roles);

It will work for both update and create.