Sling Academy
Home/PHP/How to validate nested array input in Laravel

How to validate nested array input in Laravel

Last updated: January 16, 2024

Introduction

When it comes to web development, data validation is a critical operation that ensures the data flowing through an application is accurate, secure, and useful. Laravel, a popular PHP framework, provides a powerful and flexible way to validate data coming into your application, including complex data structures like nested arrays. In this tutorial, we will explore how to validate nested array input in Laravel using various examples.

Basic Nested Array Validation

Assuming you have a form that allows users to submit data for multiple products, each with its own set of attributes, you might receive a nested array input like this:


 <input name="products[0][name]" value="Product 1">
 <input name="products[0][price]" value="100">
 <input name="products[1][name]" value="Product 2">
 <input name="products[1][price]" value="200">
 

We’ll need to ensure that each product has a name and a price, and both fields must be valid. Here’s how you can achieve that:


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

This code tells Laravel to check each product in the array, ensuring the name is not empty, is a string, and does not exceed 255 characters. Similarly, it validates that the price is numeric and non-negative.

Custom Validation Rules

If you need more complex validation logic, you can define custom rules. For example, let’s say you want to validate that each product’s price is not only numeric but also conforms to your business’s acceptable range. You can create a custom validation rule like this:

use Illuminate\Contracts\Validation\Rule;

class ValidPrice implements Rule
{
    public function passes($attribute, $value)
    {
        // Custom logic for price validation
        return $value >= 50 && $value <= 500;
    }

    public function message()
    {
        return 'The :attribute is not within the acceptable price range.';
    }
}

$request->validate([
    'products.*.price' => ['required', 'numeric', new ValidPrice],
]);

With a custom rule, you have full flexibility to implement any validation logic as per your application’s needs.

Validating Array Structures

What if your input array has multiple levels of nesting and you need to validate the structure? Let’s consider a scenario where each product can have multiple images. The input might look something like this:


 <input name="products[0][images][0]" value="image1.jpg">
 <input name="products[0][images][1]" value="image2.jpg">
 <input name="products[1][images][0]" value="image3.jpg">
 <input name="products[1][images][1]" value="image4.jpg">
 

In this case, we can use dot notation to validate each image input:


 $request->validate([
     'products.*.images.*' => 'required|string|ends_with:jpg,png,gif'
 ]);
 

This rule ensures that every image field in each product is filled, is a string type, and the file name ends with one of the specified image extensions.

Advanced Validation Scenarios

In more advanced scenarios, you may want to apply different rules based on certain conditions. Laravel’s Validator class allows for conditional validation rules. Here’s an example where we validate products and apply a discount rule only if a discount field is present:

$validator = Validator::make($request->all(), [
    'products.*.name' => 'required|string|max:255',
    'products.*.price' => 'required|numeric|min:0'
]);

$validator->sometimes('products.*.discount', 'numeric|min:0|max:100', function ($input) {
    return isset($input['products']['discount']);
});

if ($validator->fails()) {
    return back()->withErrors($validator)->withInput();
}

This `sometimes` method adds the conditional rule if the closure returns `true`. It’s a powerful feature when dealing with complex data structures.

Conclusion

Validating nested arrays in Laravel can seem intimidating at first, but with the powerful validation features provided by the framework, you can handle almost any data validation scenario. Remember to thoroughly test your validation rules to ensure data integrity and application stability.

Next Article: How to Validate Email and Password in Laravel

Previous Article: Session Blocks in Laravel: Explained with Examples

Series: Laravel & Eloquent Tutorials

PHP

You May Also Like

  • Pandas DataFrame.value_counts() method: Explained with examples
  • Constructor Property Promotion in PHP: Tutorial & Examples
  • Understanding mixed types in PHP (5 examples)
  • Union Types in PHP: A practical guide (5 examples)
  • PHP: How to implement type checking in a function (PHP 8+)
  • Symfony + Doctrine: Implementing cursor-based pagination
  • Laravel + Eloquent: How to Group Data by Multiple Columns
  • PHP: How to convert CSV data to HTML tables
  • Using ‘never’ return type in PHP (PHP 8.1+)
  • Nullable (Optional) Types in PHP: A practical guide (5 examples)
  • Explore Attributes (Annotations) in Modern PHP (5 examples)
  • An introduction to WeakMap in PHP (6 examples)
  • Type Declarations for Class Properties in PHP (5 examples)
  • Static Return Type in PHP: Explained with examples
  • PHP: Using DocBlock comments to annotate variables
  • PHP: How to ping a server/website and get the response time
  • PHP: 3 Ways to Get City/Country from IP Address
  • PHP: How to find the mode(s) of an array (4 examples)
  • PHP: Calculate standard deviation & variance of an array