• Reading time ~ 4 min
  • 28.01.2025

Validation is a critical part of any application. It ensures that the data your application processes is accurate, reliable, and secure. In Laravel, the validation process is seamless, powerful, and easy to implement. Among the various features Laravel offers, array validation is one of the most useful yet sometimes misunderstood functionalities. In this guide, we will dive deep into Laravel’s array validation and explain it in a beginner-friendly way.

What is Array Validation in Laravel?

Array validation in Laravel allows you to validate inputs that are structured as arrays. This is particularly useful when dealing with forms or APIs that accept multiple inputs under a single field name, such as:

  • A list of email addresses.
  • A collection of product options.
  • A set of uploaded files.

For example, consider a scenario where you need to validate multiple phone numbers provided by the user as a single input. Laravel’s array validation makes this not only possible but also straightforward.

Basic Array Validation

Let’s start with a simple example. Suppose you have a form field named items[] where users can submit a list of items. To validate this input, you can specify the validation rule in your controller like this:

use Illuminate\Http\Request;

public function store(Request $request)
{
    $request->validate([
        'items' => 'required|array',
    ]);
    // Proceed with storing or processing the valid data.
}

Here’s what this does:

  1. required: Ensures the items field is present in the request.
  2. array: Ensures that the value of items is indeed an array.

Validating Elements within an Array

What if you want to validate each element within the items array? For instance, you want to ensure each item is a string with a maximum length of 50 characters. Laravel allows you to use the dot notation for this:

$request->validate([
    'items' => 'required|array',
    'items.*' => 'string|max:50',
]);

Explanation:

  • items.*: Targets each element of the items array.
  • string: Ensures each element is a string.
  • max:50: Limits the length of each string to 50 characters.

If a user submits an invalid array, Laravel will return a validation error specifying the problematic element, such as items.2 must not exceed 50 characters.

Validating Arrays with Keys

In some cases, your arrays might have specific keys that need validation. For example:

$request->validate([
    'products' => 'required|array',
    'products.*.name' => 'required|string',
    'products.*.price' => 'required|numeric|min:0',
]);

Here’s what’s happening:

  • products: Ensures the products field is an array.
  • products.*.name: Ensures each product has a name field that is a required string.
  • products.*.price: Ensures each product has a price field that is a required number greater than or equal to 0.

Example Input:

[
    'products' => [
        ['name' => 'Laptop', 'price' => 1200],
        ['name' => 'Mouse', 'price' => 25]
    ]
]

Handling Validation Errors

When validation fails, Laravel automatically redirects the user back to the previous page with validation errors. You can display these errors in your Blade templates using the $errors variable:

@if ($errors->any())
    <div class="alert alert-danger">
        <ul>
            @foreach ($errors->all() as $error)
                <li>{{ $error }}</li>
            @endforeach
        </ul>
    </div>
@endif

This provides an intuitive way to inform users about any issues with their input.

Custom Validation Rules for Arrays

Sometimes, the built-in validation rules aren’t enough, and you need to implement custom logic. Laravel makes this easy by allowing you to define custom rules:

  1. Create a custom rule using the php artisan command:

    php artisan make:rule ValidPhoneNumber
    
  2. Implement the logic in the generated rule file:

    namespace App\Rules;
    
    use Closure;
    use Illuminate\Contracts\Validation\ValidationRule;
    
    class ValidPhoneNumber implements ValidationRule
    {
        public function validate(string $attribute, mixed $value, Closure $fail): void
        {
            // Example: Check if the value matches a phone number pattern
            if(!preg_match('/^\+?[0-9]{10,15}$/', $value)) {
                $fail('Invalid phone number format.');
            }
        }
        public function message()
        {
            return 'The :attribute must be a valid phone number.';
        }
    }
  3. Apply the custom rule in your validation:

    use App\Rules\ValidPhoneNumber;
    
    $request->validate([
        'contacts.*.phone' => ['required', new ValidPhoneNumber()],
    ]);

Validating Nested Arrays

You can validate deeply nested arrays by using the dot notation. For example:

$request->validate([
    'teams' => 'required|array',
    'teams.*.members' => 'required|array',
    'teams.*.members.*.name' => 'required|string',
    'teams.*.members.*.role' => 'required|string',
]);

Input Example:

[
    'teams' => [
        [
            'members' => [
                ['name' => 'Alice', 'role' => 'Developer'],
                ['name' => 'Bob', 'role' => 'Designer']
            ]
        ]
    ]
]

Tips and Best Practices

  1. Plan Your Validation Rules: Think through your data structure and validation requirements before writing the rules.
  2. Use Custom Messages: Customize error messages for better user experience.
    $request->validate([
        'items.*' => 'string|max:50',
    ], [
        'items.*.max' => 'Each item must not exceed 50 characters.',
    ]);
  3. Leverage Custom Rules: For complex scenarios, create reusable custom rules to keep your code clean.
  4. Test Your Validation: Always test different scenarios to ensure your validation works as expected.

Conclusion

Laravel’s array validation is a powerful feature that simplifies handling complex data structures. By understanding the basics and exploring advanced use cases, you can ensure your applications handle data validation effectively and provide a better user experience. Whether you’re working with simple lists or deeply nested arrays, Laravel’s validation tools have got you covered.

Comments

No comments yet
Yurij Finiv

Yurij Finiv

Full stack

ABOUT

Professional Fullstack Developer with extensive experience in website and desktop application development. Proficient in a wide range of tools and technologies, including Bootstrap, Tailwind, HTML5, CSS3, PUG, JavaScript, Alpine.js, jQuery, PHP, MODX, and Node.js. Skilled in website development using Symfony, MODX, and Laravel. Experience: Contributed to the development and translation of MODX3 i...

About author CrazyBoy49z
WORK EXPERIENCE
Contact
Ukraine, Lutsk
+380979856297

We shoot down "Shahed" drones every day. Each one downed means lives saved. But we need mobility: a van or a trailer. Every donation = another night under protection.

🚐 Van fundraiser for my unit, 1020 regiment 🎯 Goal: 500,000 ₴
🔗 Donation link 💳 4441 1111 2546 4663