0
0
LaravelHow-ToBeginner · 3 min read

How to Validate Array in Laravel: Syntax and Examples

In Laravel, you validate an array by using the array rule in your validation rules array. You can also validate each item inside the array using dot notation like field.* with other rules such as string or integer.
📐

Syntax

To validate an array in Laravel, use the array rule on the field you expect to be an array. To validate each element inside the array, use the field.* syntax with additional rules.

  • field: The name of the input field expected to be an array.
  • array: Ensures the input is an array.
  • field.*: Targets each element inside the array for individual validation.
  • Other rules: Rules like string, integer, email can be applied to each element.
php
return $request->validate([
    'items' => 'required|array',
    'items.*' => 'string',
]);
💻

Example

This example shows how to validate a request input named tags that must be an array of strings. Each tag is checked to be a string and the array itself is required.

php
<?php

use Illuminate\Http\Request;

Route::post('/submit', function (Request $request) {
    $validated = $request->validate([
        'tags' => 'required|array',
        'tags.*' => 'string|max:20',
    ]);

    return response()->json(['validated' => $validated]);
});
Output
{"validated":{"tags":["php","laravel","validation"]}}
⚠️

Common Pitfalls

Common mistakes when validating arrays in Laravel include:

  • Forgetting to use the array rule on the main field, which can cause validation to pass incorrectly.
  • Not using the field.* syntax to validate each element, so inner values are not checked.
  • Assuming the array keys are numeric and not validating keys if needed.
php
return $request->validate([
    'emails' => 'required', // Missing 'array' rule
    'emails.*' => 'email',
]);

// Correct way:
return $request->validate([
    'emails' => 'required|array',
    'emails.*' => 'email',
]);
📊

Quick Reference

RuleDescription
arrayEnsures the input is an array
field.*Targets each element inside the array for validation
stringValidates each element is a string
integerValidates each element is an integer
requiredField must be present and not empty

Key Takeaways

Always use the 'array' rule to confirm the input is an array.
Use 'field.*' syntax to validate each element inside the array.
Combine element rules like 'string' or 'integer' with 'field.*' for precise validation.
Forget not to mark the array field as 'required' if it must be present.
Common errors come from missing the 'array' rule or not validating elements individually.