Hi I wonder if it possible to validate an array like this in laravel:
Array
(
[0] => John
[1] => 20
[2] => john@example.com
)
because im getting the data from the excel file. I want to validate the [1] => numeric
and [2] => email
.
Thanks.
You need to create a custom validation like following.
Validator::extend('check_my_array', function ($attribute, $value, $parameters, $validator) {
$validation = [];
foreach($parameters as $parameter)
$validation[] = "required|{$parameter}";
$validator = Validator::make($value, $validation);
return !$validator->fails();
});
You can create ValidatorServiceProvider and you can add these lines to boot method of ValidatorServiceProvider. Then you need to add Provider to your providers array in config/app.php.
App\Providers\ValidatorServiceProvider::class,
Or you just add them top of the action of your controller.
At the end you can use it like this in your validation rules.
$validator = Validator::make(
['array' => ['John', 'asd', 'john@example.com']],
['array' => 'check_my_array:,numeric,email']
);
if ($validator->fails())
dd('fail');
else dd('success');
Note: Everything after the check_my_array separated by comma is a parameter we use them specific rule for elements of the array.