Array validation is slightly different from other column validation in the laravel application. We can validate normal array keys and also nested array keys in Laravel. There are a bunch of validation functions in Laravel.

In this tutorial, I will show you how to validate array keys in laravel and how to validate nested array keys in Laravel. We will see examples one by one and I will try to clarify your doubts about Laravel array validation.

Let's see the first example of laravel associative array validation:

<?php 

$input = [
    'country' => [
        'name' => 'Bangladesh',
        'area' => '147000',
        'is_ashian' => true,
    ],
];
 
$validator = Validator::make($input, [
    'country' => 'array:name,area',
]);

if (!$validator->valid()) {
    return $validator->errors();
}

 

Look at that, the above validation was without using validation rules. Now we will see how to validate arrays in Laravel using validation rules.

<?php

$data = $request->validate([
    'facilities' => 'required|array|min:2',
    'facilities.*' => 'string|in:wifi,fridge,sports_room,prayer_room'
]);

 

Now let's see the example of how to validate nested array in Laravel:

<?php

$data = $request->validate([
    'country.*.name' => 'required',
    'country.*.area' => 'required|email',
]);

 

For this above validation, HTML input will look like this:

<div class="card">
    <input type="text" name="country[{{ $i }}][name]" placeholder="Name">
    <input type="text" name="country[{{ $i }}][area]" placeholder="Area">
</div>

 

Read also: Old Value In Multiple Select Option In Laravel Blade

 

Conclusion

Now we know laravel validation and laravel validate array keys. Now we know how to validate laravel request array validation. Hope this laravel validation array not empty tutorial will help you.