Laravel validation rule "same" raising error instead of adding validation error to messsage bag

75 Views Asked by At

A part of my laravel 10.x controller is given below:

$validator = Validator::make($request->all(), [
            'email' => 'required|email|unique:users,email',
            'password' => 'required|min:8',
            'password_confirm' => 'required|min:8|same:password',
            'avatar' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
            'f_name' => 'required|string|min:3|max:50',
            'l_name' => 'required|string|min:3|max:50',
            'designation' => 'nullable|string|max:50',
            'permissions' => 'required|array'
], $messages = [
            'password_confirm.same' => 'password must match with password confirm',
]);

if ($validator->fails()) {
            return response()->json([
                'message' => 'Validation failed',
                'validation_errors' => $validator->getMessageBag(),
            ], 422);
}

I expecting that, it return validation error messages in 'validation_errors' => $validator->getMessageBag(),. But instead of adding validation errors to validation error message bag, it raising an error in laravel.log file :

[2023-09-05 06:31:00] local.ERROR: The password confirm field must match password. (and 3 more errors)  
1

There are 1 best solutions below

0
yahya sghayron On

Laravel's validation rule "same" throws an error by default when it fails instead of adding an error message to the message bag. If you want to prevent this error from being thrown and instead add a custom error message to the message bag, you can use a workaround by manually adding the error to the message bag. Here's how you can do that:

$validator = Validator::make($request->all(), [
    'email' => 'required|email|unique:users,email',
    'password' => 'required|min:8',
    'password_confirm' => 'required|min:8',
    'avatar' => 'nullable|image|mimes:jpeg,png,jpg,gif,svg|max:2048',
    'f_name' => 'required|string|min:3|max:50',
    'l_name' => 'required|string|min:3|max:50',
    'designation' => 'nullable|string|max:50',
    'permissions' => 'required|array'
]);

// Add a custom error message for the "password_confirm" field if it fails the "same" rule
if ($request->input('password') !== $request->input('password_confirm')) {
    $validator->errors()->add('password_confirm', 'The password confirmation does not match.');
}

if ($validator->fails()) {
    return response()->json([
        'message' => 'Validation failed',
        'validation_errors' => $validator->getMessageBag(),
    ], 422);
}

In this code, we perform the "same" rule check manually by comparing the "password" and "password_confirm" fields. If they don't match, we add a custom error message to the validation error message bag for the "password_confirm" field. This way, you can prevent the "same" rule from raising an error and handle it within your validation logic.