Validating Arrays in Laravel
When attempting to validate an array in Laravel using the following code:
$validator = Validator::make($request->all(), [ "name.*" => 'required|distinct|min:3', "amount.*" => 'required|integer|min:1', "description.*" => "required|string" ]);
You may encounter an unexpected scenario where an empty POST submission is mistakenly recognized as valid, resulting in a false positive.
This confusion arises because the asterisk symbol (*) in the code is intended to validate the values within the array, not the array itself. To address this, the validation rules should be modified to check for the presence of the array:
$validator = Validator::make($request->all(), [ "names" => "required|array|min:3", "names.*" => "required|string|distinct|min:3", ]);
In this adjusted code:
Since Laravel 5.5, a simplified approach can be employed:
$data = $request->validate([ "names" => "required|array|min:3", "names.*" => "required|string|distinct|min:3", ]);
This compact syntax directly performs validation on the Request object, eliminating the need for the $validator intermediary.
The above is the detailed content of How to Validate Arrays in Laravel: Empty Submissions and Best Practices?. For more information, please follow other related articles on the PHP Chinese website!