Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I validate an array of integers in Laravel

Tags:

I have an array of integer like this $someVar = array(1,2,3,4,5). I need to validate $someVar to make sure every element is numeric.How can I do that?

I know that for the case of a single valued variable, the validation rule would be something like this $rules = array('someVar'=>'required|numeric'). How can I apply the same rule to every element of the array $someVar?

Thanks a lot for helping.

like image 975
Kola Avatar asked Jul 05 '14 17:07

Kola


People also ask

How do I validate an array in Laravel?

you can call validate() method directly on Request object like so: $data = $request->validate([ "name" => "required|array|min:3", "name. *" => "required|string|distinct|min:3", ]);

How do I validate a form request in Laravel?

For more complex validation scenarios, you may wish to create a “form request.” Form requests are the custom request classes that contain validation logic. To create a form request class, use the make: request Artisan CLI command. It will create a file inside the app >> Http >> Requests folder called FieldRequest.

What is confirmed validation in Laravel?

By default, Laravel 'confirmed' validator adds the error message to the original field and not to the field which usually contains the confirmed value.


1 Answers

Now laravel has option to set condition on array elements. No need to write your own validator for simple things like validation int array. Use this (if using in controller)-

$validator = \Validator::make(compact('someVar'), [     'someVar' => 'required|array',     'someVar.*' => 'integer' ]); $this->validateWith($validator); 

or

$this->validate($request, [     'someVar' => 'array',     'someVar.*' => 'int' ]); 
like image 107
Aayush Anand Avatar answered Oct 04 '22 06:10

Aayush Anand