Following C(reate), R(ead), U(pdate), D(elete) methods, your Create and Update should be distinct.
So best to separate your routes into 2, so that you have create (store) with a POST method and update with PATCH method.
if you know the user_id then you know you should be updating
Password should be optional if you are updating as a user may not want to update.
public function store(Request $request)
{
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users,email,' . $request->user_id,
'password' => 'required',
'role' => 'required',
]);
$user = User::create([
'name' => $request->name,
'email' => $request->email,
'role' => $request->role,
'password' => Hash::make($request->password)
]);
}
public function update(Request $request, User $user)
{
$validated = $request->validate([
'name' => 'required',
'email' => 'required|email|unique:users,email,' . $request->user_id,
'password' => 'optional',
'role' => 'required',
]);
$user = User::update($validated);
}
Additionally it can get a bit messy if you are adding conditional checks if you are making the request with AJAX. AJAX requests should respond with a json body and a HTTP response code, and normal requests will respond with a redirect.
I would separate your AJAX requests into separate methods again, and these can be prefixed with api
so
Standard:
- POST /your-controller - hits YourController::store
- PATCH /your-controller - hits YourController::update
Ajax
- POST /api/your-controller - hits API/YourController::store
- PATCH /api/your-controller - hits API/YourController::update
This may seem like overkill but what you'll end up with is 4 very small easy to understand methods, rather than 1 with a load of if statements in it.