Laravel 12 Array Validation Example

In this Laravel 12 tutorial, you’ll learn how to validate array inputs with examples.

Laravel provides powerful validation rules that make it easy to work with array form fields such as multiple checkboxes, dynamic inputs, or nested data.

What is Array Validation?

Array validation in Laravel allows you to validate data that comes in array format, such as multiple form inputs like contact details, addresses, or products.

Laravel provides an elegant and powerful way to validate array-based form inputs without writing complex loops or logic.

Why Use Array Validation?

In modern web applications, you often have forms that send data as arrays.

For example:

  • Multiple tags or categories selection
  • Repeating input fields (like multiple phone numbers)
  • Dynamic forms using JavaScript

Laravel’s validation system makes it simple to validate these arrays using rules like array, min, max, distinct, and even nested rules using dot notation.

Simple Array Validation Example

Step 1: Create view

In this step, we create a Blade view (form.blade.php) to handle array validation in Laravel. This form allows users to submit multiple product images at once.

  • The form uses enctype=”multipart/form-data” to handle file uploads.
  • The input field uses name=”product_imgs[]” with the multiple attribute so users can select multiple images.
  • Laravel will automatically validate each uploaded image based on the rules defined in the controller.
  • Validation errors are displayed at the top, and successful submissions show a success alert.
<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel 12 Array Validation Example - ItStuffSolutiotions</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <!-- Bootstrap 5.3.8 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="card mt-5 shadow-lg border-0">
        <h3 class="card-header p-3 bg-primary text-white">
            Laravel 12 Array Validation Example - ItStuffSolutiotions
        </h3>
        <div class="card-body">
           @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            @session('success')
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                    {{ session('success') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            @endsession
            <form method="POST" action="{{ route('validate') }}" enctype="multipart/form-data">
                @csrf
                <div class="mb-3">
                    <label class="form-label">Images:</label>
                    <input 
                        type="file"
                        name="product_imgs[]"
                        class="form-control "
                        multiple
                        >                     

                </div>               
                
                <div class="mb-3">
                    <button class="btn btn-success btn-submit">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>
 
<!-- Bootstrap 5.3.8 JS (with Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Step 2: Validation Logic In Controller

In this step, we created a UserController and wrote the logic for array form validation. Laravel automatically validates each uploaded image, ensuring all inputs meet the specified rules.

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;

 
class UserController extends Controller
{    
     /**
     * Show the application form.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(): View
    {
        return view('form');
    }
 
     /**
     * Store data.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    {
 
            $request->validate([
            'product_imgs' => 'required|array|min:2|max:5',
            'product_imgs.*' => 'required|image|mimes:jpg,jpeg,png|max:2048',
            ]);
           
        
             
        return back()->with('success', 'Product images saved successfully.');
    }
}

Explanation

  • product_imgs : Must be an array of files, required, with minimum 2 and maximum 5 images.
  • product_imgs.* : Validates each file inside the array:
    • Must exist (required)
    • Must be an image
    • Only jpg, jpeg, png formats allowed
    • Max size 2 MB per file

This ensures users upload 2–5 valid images (JPG/PNG), each under 2MB, keeping uploads safe and consistent.

Step 3: Update Routes

In this step, we define two routes: GET route to Displays the form view and POST route Handles form submission and validates the input, showing errors if any. Open routes/web.php

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
    
Route::get('custom-validation', [UserController::class, 'create']);
Route::post('custom-validation', [UserController::class, 'store'])->name('validate');

Nested Array Validation

In this example, you will learn how to validate nested array fields in Laravel. Suppose you have a form where users can add multiple products at once, each with a name and a price.

Step 1: Update view

Update form.blade.php to include multiple product fields using nested array syntax (products[0][name], products[0][price], etc.), which allows Laravel to validate each product individually.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel 12 Array Validation Example - ItStuffSolutiotions</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <!-- Bootstrap 5.3.8 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="card mt-5 shadow-lg border-0">
        <h3 class="card-header p-3 bg-primary text-white">
            Laravel 12 Array Validation Example - ItStuffSolutiotions
        </h3>
        <div class="card-body">
           @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            @session('success')
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                    {{ session('success') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            @endsession
            <form method="POST" action="{{ route('validate') }}" enctype="multipart/form-data">
                @csrf
                <div class="mb-3">
                    <label class="form-label">Product Name:</label>
                   <input type="text" name="products[0][name]" placeholder="Product Name" class="form-control" >
                </div>
                <div class="mb-3">
                   <label class="form-label">Product Price:</label>
                   <input type="text" name="products[0][price]" placeholder="Product Price" class="form-control" >
                </div>
                 <div class="mb-3">
                    <label class="form-label">Product Name:</label>
                   <input type="text" name="products[1][name]" placeholder="Product Name" class="form-control" >
                </div>
                <div class="mb-3">
                   <label class="form-label">Product Price:</label>
                   <input type="text" name="products[1][price]" placeholder="Product Price" class="form-control" >
                </div> 
                
                <div class="mb-3">
                    <button class="btn btn-success btn-submit">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>
 
<!-- Bootstrap 5.3.8 JS (with Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Read Also : Laravel 12 Custom Validation Error Messages Example

Step 2: Controller Logic for Nested Array Validation

In this step, we will update the store() method to handle nested array validation. This function processes the form submission and ensures that each product in the products array meets the validation rules.

<?php
 
 
      /**
     * Store data.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    { 
 
           $request->validate([
                'products' => 'required|array|min:1',
                'products.*.name' => 'required|string|max:100',
                'products.*.price' => 'required|numeric|min:1',
            ]);
          
        
             
        return back()->with('success', 'Product details saved successfully.');
    }

Laravel 12 Array Validation Example
Laravel 12 Array Validation Form preview
  • Laravel checks each product individually using the * wildcard.
  • If validation passes, the user is redirected back with a success message: “Product details saved successfully.”

Validating the Structure of an Array

Step 1: Create view

In this step, we’ll update the Blade view to validate the array structure. We’re using a contacts array that contains two specific keys: email(name=”contacts[email]”) and phone(name=”contacts[phone]”).

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Laravel 12 Array Validation Example - ItStuffSolutiotions</title>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 
    <!-- Bootstrap 5.3.8 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
    <div class="card mt-5 shadow-lg border-0">
        <h3 class="card-header p-3 bg-primary text-white">
            Laravel 12 Array Validation Example - ItStuffSolutiotions
        </h3>
        <div class="card-body">
           @if ($errors->any())
                <div class="alert alert-danger">
                    <ul>
                        @foreach ($errors->all() as $error)
                            <li>{{ $error }}</li>
                        @endforeach
                    </ul>
                </div>
            @endif

            @session('success')
            <div class="alert alert-success alert-dismissible fade show" role="alert">
                    {{ session('success') }}
                    <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                </div>
            @endsession
            <form method="POST" action="{{ route('validate') }}" enctype="multipart/form-data">
                @csrf
                <div class="mb-3">
                    <label class="form-label">Phone:</label>
                   <input type="text" name="contacts[phone]" class="form-control" placeholder="Phone">
                </div>
                <div class="mb-3">
                   <label class="form-label">Email:</label>
                   <input type="email" name="contacts[email]" class="form-control" placeholder="Email">
                </div> 
                
                <div class="mb-3">
                    <button class="btn btn-success btn-submit">Submit</button>
                </div>
            </form>
        </div>
    </div>
</div>
 
<!-- Bootstrap 5.3.8 JS (with Popper) -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.8/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

Step 2: Array Structure Validation Logic in Controller

You can also tell Laravel exactly which keys are expected in your array.

  • This ensures the contacts array must include both phone and email keys.
  • If one of them is missing or if there’s an extra unexpected key, validation fails.

This helps keep your data format clean and predictable.

<?php
 
namespace App\Http\Controllers;
 
use Illuminate\View\View;
use Illuminate\Http\Request;
use Illuminate\Http\RedirectResponse;

 
class UserController extends Controller
{    
     /**
     * Show the application form.
     *
     * @return \Illuminate\Http\Response
     */
    public function create(): View
    {
        return view('form');
    }
 
     /**
     * Store data.
     *
     * @return \Illuminate\Http\Response
     */
    public function store(Request $request): RedirectResponse
    { 
 
           $request->validate([
                'contacts' => 'required|array:phone,email',
            ]);
          
        
             
        return back()->with('success', 'contact details saved successfully.');
    }
}

Custom Error Messages

Good validation is not just about catching errors it’s also about giving friendly, clear feedback to the user.

Laravel lets you define custom error messages for each rule, including nested array fields like products.*.name or products.*.price. After customizing error messages validation error messages look like this :

Laravel array validation custom error message
Laravel array validation custom error message
 $request->validate([
                'products' => 'required|array|min:1',
                'products.*.name' => 'required|string|max:100',
                'products.*.price' => 'required|numeric|min:1',
           ], [
            'products.array' => 'The product field must be an array.',
            'products.min' => 'Please add at least one product.',
            'products.*.name.required' => 'Each product must have a name.',
            'products.*.name.string' => 'Product name must be a valid text.',
            'products.*.name.max' => 'Product name cannot exceed 100 characters.',
            'products.*.price.required' => 'Each product must have a price.',
            'products.*.price.numeric' => 'Product price must be a valid number.',
            'products.*.price.min' => 'Product price must be at least ₹1.',
        ]);

  • Notice the * (asterisk) it’s a wildcard that applies the same rule and message to every product in the array.
  • So if you have 5 products and the 3rd one is missing a name, Laravel will automatically use: “Each product must have a name.”

Now, if a user forgets to add product name and price in any products, they’ll see a helpful message.

Conclusion

Array validation in Laravel 12 makes handling complex input data clean, predictable, and secure.

By defining validation rules for arrays whether for a single-level structure like contacts[email] and contacts[phone], or nested structures like products[0][name] and products[0][price] you ensure that the submitted data always follows a consistent format.

The array: rule helps enforce which keys are expected, while the * (wildcard) syntax allows you to validate every element in a nested array easily.

On top of that, Laravel’s custom error messages make validation user-friendly by providing clear and meaningful feedback instead of technical error text.

In short, mastering array validation empowers you to:

  • Keep form data well-structured
  • Prevent missing or malformed entries
  • Provide clear, human-readable feedback to users

With these techniques, your Laravel forms will not only be robust but also deliver a smooth and professional user experience.