How to Properly Validate Arrays in Laravel?

Patricia Arquette
Release: 2024-11-25 00:00:44
Original
859 people have browsed it

How to Properly Validate Arrays in Laravel?

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",
]);
Copy after login

Explanation

In this example:

  • "names" checks if the array itself exists and has at least 3 elements.
  • "names.*" validates the individual values in the "names" array, ensuring they are strings, distinct, and at least 3 characters long.

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",
]);
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template