skip to Main Content

my email unique validation is not working.

From this form, I am sending a user

<form id="edit-form" class="mt-4" action="{{ route('user.update', 1) }}" method="post">
    @csrf @method('put')
</form>

It goes here to my web.php

Route::prefix('/user')->group(function () {
   Route::put('/update/{user}', [AppHttpControllersUserController::class, 'update'])->name('user.update');
});

Then it comes here in the controller

public function update(UpdateUserRequest $request)
{
    dd($request);
}

Which calls this request form:

public function rules(): array
{
    return [
        'email' => ['nullable', Rule::unique('users', 'email')->ignore($this->id, 'id'), 'email:rfc', 'max:255'],
    ];
}

Yet everytime, if I send the same email the model already has, it will say that the email is already in use.

2

Answers


  1. Provided that you use this route definition for your update route:

    Route::put('update/{user}', [AppHttpControllersUserController::class, 'update'])->name('user.update');
    

    When using the route helper, you should pass in an entire user model:

    <form id="edit-form" class="mt-4" action="{{ route('user.update', ['user' => $user]) }}" method="post">
        @csrf @method('put')
    </form>
    

    You should update the update method on your UserController:

    public function update(UpdateUserRequest $request, User $user)
    {
        //
    }
    

    In your UpdateuserRequest you will now be able to simply do this:

    Rule::unique('users', 'email')->ignore($this->user)
    
    Login or Signup to reply.
  2. putting here, its not formatting in comment. Its not the actual solution but worked for me inside the controller, try it, if that works it should work in validation request class as well.

    public function update(Request $request, $id)
        {
            $validator = Validator::make($request->all(), [
                'email' => ['nullable', Rule::unique('users', 'email')->ignore($id), 'email:rfc', 'max:255'],
            ]);
    
            if ($validator->fails()) {
                return response()->json($validator->errors());
            }
    
            return response('updated');
        }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search