Get ID of user being updated inside Form Request to ignore validation when updating same user

42 Views Asked by At

When updating a specific user, I want to run unique validation for the 'username' and 'studentNumber' fields, but only for other users and not for the same user being updated because its already owned by them. If I use unique:users only, it will cause errors when updating because it will run the validation against the user themselves. Instead, I used Rule::unique('users')->ignore($user->id) to ignore the user being updated, but I need to pass the id of the user being updated to the Form Request. How do I accomplish this?

UserController.php

    public function update(UpdateUserRequest $request, string $id)
    {
        try{
            DB::table('users')->where('id',$id)->update($request->validated());
        }catch(Exception $ex){
            return response()->json(['message' => $ex->getMessage()], 409);

        }

    }

UpdateUserRequest.php

    public function rules(): array
    {
        return [
            'username' => [  Rule::unique('users')->ignore($user->id), 'string', 'max:255'],
            'studentNumber' => [ Rule::unique('users')->ignore($user->id), 'string'],

        ];
    }
1

There are 1 best solutions below

3
imaginabit On

Why don't you just validate first and then try the update?

you can use one of this two examples:

public function update(UpdateUserRequest $request, string $id)
{
    $validator = Validator::make($request->all(), $request->rules());
    if ($validator->fails()) {
        return response()->json(['errors' => $validator->errors()], 422);
    }

    $user = User::findOrFail($id);
    $user->update($request->all());
    ...

public function update(UpdateUserRequest $request, string $id)
{
    $validData = $request->validated();
    // if not valid it throws error or anything you change in failedValidation() method 

    $user = User::findOrFail($id);
    $user->update($validData);
    ...