DEV Community

Cover image for Laravel 12 Array Validation Example
itstuffsolutions
itstuffsolutions

Posted on • Originally published at itstuffsolutiotions.io

Laravel 12 Array Validation Example

When building modern applications, it’s common to handle multiple inputs or repeating form fields such as multiple images, phone numbers, or product details. Laravel simplifies this with its powerful array validation feature.

What Is Array Validation in Laravel?
Array validation enables you to validate form data that comes as an array for example, a group of uploaded files or dynamically generated input fields.

Instead of writing complex loops or manually checking each value, Laravel lets you define concise and expressive validation rules for entire arrays and their individual elements.

Why Use Array Validation?

In many dynamic web forms, you’ll often collect:

  • Multiple images or attachments
  • A list of product details
  • Several phone numbers or addresses
  • Multiple tags or categories

Laravel’s validation system makes this process simple using rules like array, min, max, and even nested validation with dot notation.

Example: Validate Multiple Uploaded Images

Let’s create a simple example to validate multiple image uploads in Laravel.

Step 1: Create a Blade Form View

We’ll start by creating a Blade file named form.blade.php, which allows users to upload multiple images at once.

<!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>

Enter fullscreen mode Exit fullscreen mode

The input field uses name="product_imgs[]" and the multiple attribute so that Laravel recognizes it as an array input.

What’s Happening Here

  • Users can upload multiple files at once.
  • Laravel automatically handles the array input.
  • Any validation errors are shown above the form.

Step 2: Write Validation Logic in the Controller

Now, let’s define the validation logic inside a UserController.

<?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.');
    }
}

Enter fullscreen mode Exit fullscreen mode

Explanation

  • product_imgs: Must be an array with at least 2 and at most 5 items.
  • product_imgs.* : Applies rules to each file:
  • Required
  • Must be an image
  • Must be JPG, JPEG, or PNG
  • Max size of 2MB per file

This ensures only valid image files are accepted and prevents users from uploading too many or invalid files.

Step 3: Define Routes

Now register the form and validation routes inside your routes/web.php file.

<?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'); 

Enter fullscreen mode Exit fullscreen mode

Nested Array Validation Example

Laravel also supports validating nested arrays, which is useful when dealing with complex data structures for example, multiple products, each with its own name and price.

Using dot notation, you can define validation rules like this:

$request->validate([
    'products' => 'required|array|min:1',
    'products.*.name' => 'required|string|max:100',
    'products.*.price' => 'required|numeric|min:1',
]); 
Enter fullscreen mode Exit fullscreen mode

This ensures every product in the array has a valid name and price field.

👉 Read full article here: Laravel 12 Array Validation Example

Top comments (0)