0

I am trying to validate a multi dimensional array in Laravel. This whole input itself is not required, however, if it is present, all of its keys should have some value.

My Input has dynamic input arrays. Example :

 $users = [    
    ['name' => 'John' , 'Age' => 25],    
    ['name' => 'Nick' , 'Age' => 28] 
 ]

My requirement is that, if a record is sent along with the request, it has to contain both name and age. At the same time, this whole array is not mandatory.

I can accept

$users = [] 

Cannot accept

$users = [    
    ['name' => '' , 'Age' => 25],    
    ['name' => 'Nick' , 'Age' => null] 
 ]

3 Answers 3

1

Something like that in your Request should work:

public function rules()
{
    return [
        'users' => 'array', //add 'sometimes' if the array can be null other than empty
        'users.*.name' => 'required',
        'users.*.Age' => 'required',
    ]
}

This return false if any of the user is missing name or Age attributes.

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

Comments

0

I like @Shafeel's solution - Here is another way to go around:

if(count($users >= 1){
  foreach($users as $user) {
    if(empty($user->name) || empty($user->age) {
      return false; //break the loop and return with error message
    }
  }
}

Comments

0

You can validate an array as an optional or sometimes a validation rule inside a validator.

public function rules()
{
    return [
        'users' => 'sometimes|array',
        'users.*.name' => 'sometimes',
        'users.*.Age' => 'sometimes',
    ]
}

** OR you can**

public function rules()
{
    return [
        'users' => 'optional|array',
        'users.*.name' => 'optional',
        'users.*.Age' => 'optional',
    ]
}

Comments

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.