1
<input type="text" name="name[2]">

I tried validate like this, but didn't work correctly

$valid = Validator::make($request->all(), [
    //'name.2' => 'required',
    'name[2]' => 'required',
]);

-- Laravel Framework version 5.3.26

2 Answers 2

5

A nice way would be using Form Requests and creating dynamic rules for your arrays, like this

public function rules()
{
  $rules = [
    'name' => 'required|max:255',
  ];

  foreach($this->request->get('items') as $key => $val)
  {
    $rules['items.'.$key] = 'required|max:10';
  }

  return $rules;
}

Here's a nice article talking about this: https://ericlbarnes.com/2015/04/04/laravel-array-validation/

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

1 Comment

I know that article. I think like my first rule 'name.2'. But didn't work too,,, :(
3

You may also validate each element of an array. For example, to validate that each e-mail in a given array input field is unique, you may do the following:

$validator = Validator::make($request->all(), [
   'person.*.email' => 'email|unique:users',
   'person.*.first_name' => 'required_with:person.*.last_name', 
]);

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.