How do I validate an array of integers in Laravel
Validator::extend('numericarray', function($attribute, $value, $parameters)
{
foreach($value as $v) {
if(!is_int($v)) return false;
}
return true;
});
Use it
$rules = array('someVar'=>'required|array|numericarray')
Edit:
Up to date version of this validation would not require the definition of numericarray
method.
$rules = [
'someVar' => 'required|array',
'someVar.*' => 'integer',
];
In Laravel 5 you can check the elements in an array by using .*
. For you this would mean:
$rules = array('someVar' => 'required|array',
'someVar.*' => 'integer')
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'
]);