Laravel Validation Array Validation


Example

Validating array form input fields is very simple.

Suppose you have to validate each name, email and father name in a given array. You could do the following:

$validator = \Validator::make($request->all(), [
    'name.*'       => 'required', 
    'email.*'      => 'email|unique:users',
    'fatherName.*' => 'required'
]);

if ($validator->fails()) {
    return back()->withInput()->withErrors($validator->errors());
}

Laravel displays default messages for validation. However, if you want custom messages for array based fields, you can add the following code:

[
    'name.*' => [
        'required' => 'Name field is required',
    ],
    'email.*' => [
        'unique'   => 'Unique Email is required',
    ],
    'fatherName.*' => [
        'required' => 'Father Name required',
    ]
]

Your final code will look like this:

$validator = \Validator::make($request->all(), [
    'name.*'       => 'required', 
    'email.*'      => 'email|unique:users',
    'fatherName.*' => 'required',
], [
    'name.*'       => 'Name Required',
    'email.*'      => 'Unique Email is required',
    'fatherName.*' => 'Father Name required',
]);

if ($validator->fails()) {
    return back()->withInput()->withErrors($validator->errors());
}