Array Validation in Laravel
You're encountering validation issues when dealing with array data in Laravel. When submitting an empty POST request, you expect validation to fail, but it returns as true.
Solution
The issue lies in how you're validating the array. The asterisk (*) symbol in Laravel validates the individual values within the array, not the array itself. To validate the array, use the following syntax:
$validator = Validator::make($request->all(), [ "names" => "required|array|min:3", "names.*" => "required|string|distinct|min:3", ]);
Explanation
In this example:
With this updated validation logic, empty POST requests will fail as expected.
Validation Improvements in Laravel 5.5
Starting with Laravel 5.5, you can use a simplified syntax for array validation by calling the validate() method directly on the Request object:
$data = $request->validate([ "names" => "required|array|min:3", "names.*" => "required|string|distinct|min:3", ]);
The above is the detailed content of How to Properly Validate Arrays in Laravel?. For more information, please follow other related articles on the PHP Chinese website!