Validating Arrays with Laravel
When working with arrays in Laravel, it's crucial to validate them appropriately. However, users may encounter issues with validation when sending an empty POST array.
To clarify, the asterisk symbol (*) in Laravel's validation rules is used to validate values within an array, not the array itself. This can lead to confusion when expecting validation to fail for an empty array.
Solution
To validate an array correctly, you should follow this updated syntax:
$validator = Validator::make($request->all(), [ "names" => "required|array|min:3", "names.*" => "required|string|distinct|min:3", ]);
Breaking Down the Validation Rules
In this example:
Note for Laravel 5.5 and Above
In Laravel 5.5 and above, you can directly call the validate() method on the Request object:
$data = $request->validate([ "name" => "required|array|min:3", "name.*" => "required|string|distinct|min:3", ]);
The above is the detailed content of How to Validate Arrays Effectively in Laravel?. For more information, please follow other related articles on the PHP Chinese website!