Laravel validate array of data

Working with a web application there will be a time when you come across to validate an array of data or an array of object data to make sure it fits with some type of specific data format. This article will give you some examples of how to validate array data in the Laravel framework.

Create a request to validate

Assuming we validate a list of products to bulk insert into the database.

php artisan make:request ProductImportRequest

After running the command above you will see ProductImportRequest in the app/Http/Requests. In the ProductImportRequest.php

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

class ProductImportRequest extends FormRequest
{
    /**
     * Determine if the user is authorized to make this request.
     *
     * @return bool
     */
    public function authorize()
    {
        return true;
    }

    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            "*.name" => "required|max:255|distinct|unique:products,name",
            "*.price" => "required|digits_between:1,9|regex:/^\d*(\.\d{1,2})?$/"
        ];
    }
}

The * symbol represents the index of the array basically “*.name” meaning to validate “0.name”, “1.name”, “2.name”....

Sample controller to insert

In the ProductController.php

public function import(ProductImportRequest $request)
{
    Product::insert($request->get('data'));
    return response()->json(["data" => [
        "success" => true
    ]]);
}

JSON Data

[
	{
		"name": "Product 1",
		"price": "10"
	},
	{
		"name": "Product 2",
		"price": "19.99"
	},
	{
		"name": "Product 3",
		"price": "123456.99"
	}
]

JSON Data (Different format)

{
	"data": [
		{
			"name": "Product 1",
			"price": "10"
		},
		{
			"name": "Product 2",
			"price": "19.99"
		},
		{
			"name": "Product 3",
			"price": "123456.99"
		}
	]
}

Validate

public function rules()
{
    return [
        "data.*.name" => "required|max:255|distinct|unique:products,name",
        "data.*.price" => "required|digits_between:1,9|regex:/^\d*(\.\d{1,2})?$/"
    ];
}

This will validate data.0.name, data.1.name, data.2.name….

Conclusion

Laravel provides a really easy-to-validate array of data using only it's built-in validate. The article above will give you all the samples necessary needed to validate array data.