Ad

How To Use Laravel Bail Validation?

- 1 answer

I use Bail rule on each validation request and I expect it stop on first validation exception and don't validate other request params. But it validate all input data.

MyController.php

public function update(Request $request)
    {
        $user = auth()->user();
        $request->validate([
            'name' => ['bail','string'],
            'email' => ['bail','email', Rule::unique('users')->ignore($user->id)],

        ]);
        $user->update(request()->only('name', 'email'));
        return response()->json($user);
    }

Request Data:

{name: "example", email: "[email protected]"}

Response:

{
    "message": "The given data was invalid.",
    "errors": {
        "name": [
            "The name field is required."
        ],
        "email": [
            "The email has already been taken."
        ]
    }
}

What's the problem?

Ad

Answer

The bail validation rule applies to a "multi-rule" attribute. It does not stop running validation for other attributes. From the documentation:

$request->validate([
    'title' => 'bail|required|unique:posts|max:255',
    'body' => 'required',
]);

If the unique rule on the title attribute fails, the max rule will not be checked.

Ad
source: stackoverflow.com
Ad