0

I have a input request that can be an integer or an array of integer values.

How can I check validation of that in Laravel? I'm using Laravel 5.5.I know that there is a simple array validation rules that checks an input is an array or not:

array

The field under validation must be a PHP array.

Is there any predefined validation rule or should I write a new one? if yes, How?

3
  • you can create same custom validation rules, which will check if you input field is and array or just un integer Commented Nov 28, 2017 at 8:03
  • each array elements should be an integer . how to check it ? Commented Nov 28, 2017 at 8:09
  • Laravel Valadating arrays Commented Nov 28, 2017 at 8:23

1 Answer 1

0
$input = $request->all();

//Check if input param is an array
if(is_array($input['item']))
{
  //Array validator
  $Validator = Validator::make($input, 
    [
        'item' => 'required', //Array with key 'item' must exist
        'item.*' => 'sometimes|integer', //All values should be integers
    ]);
}
else
{
  //Integer validator
  $Validator = Validator::make($input, 
    [
        'item'   => 'required|integer',
    ]);
}

Use sometimes it applies validation rule only if that input parameter exist. Hope this helps

Sign up to request clarification or add additional context in comments.

3 Comments

How can I write it as a custom validation rule for next uses
Its up to you. You can use either ways. Above solution will work for you I think. It will save your time and efforts :)
@A.B.Developer did you find this helpful ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.