Wirasto
Wirasto

Reputation: 88

How to validate array input in laravel?

<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

Upvotes: 1

Views: 7569

Answers (2)

Mokariya Sanjay
Mokariya Sanjay

Reputation: 194

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', 
]);

Upvotes: 3

Antonio Carlos Ribeiro
Antonio Carlos Ribeiro

Reputation: 87719

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/

Upvotes: 5

Related Questions