How to validate array in Laravel?

Darama picture Darama · Feb 15, 2017 · Viewed 153.9k times · Source

I try to validate array POST in Laravel:

$validator = Validator::make($request->all(), [
            "name.*" => 'required|distinct|min:3',
            "amount.*" => 'required|integer|min:1',
            "description.*" => "required|string"

        ]);

I send empty POST and get this if ($validator->fails()) {} as False. It means that validation is true, but it is not.

How to validate array in Laravel? When I submit form with input name="name[]"

Answer

Filip Sobol picture Filip Sobol · Feb 15, 2017

Asterisk symbol (*) is used to check values in the array, not the array itself.

$validator = Validator::make($request->all(), [
    "names"    => "required|array|min:3",
    "names.*"  => "required|string|distinct|min:3",
]);

In the example above:

  • "names" must be an array with at least 3 elements,
  • values in the "names" array must be distinct (unique) strings, at least 3 characters long.

EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:

$data = $request->validate([
    "name"    => "required|array|min:3",
    "name.*"  => "required|string|distinct|min:3",
]);