Validate uniqueness in an Array with Laravels Validator

Published in Development, Laravel on Apr 11, 2023

Did you know Laravels Validator class is well equiped to deal with Arrays?

Today I needed some form validation to make sure every item in an array was referencing its own distinct product.

Imagine a simple Livewire component to create an order that could look like this:

class OrderFormComponent extends Component
{
    public Collection $orderLines;

    public function addLine(int $productId, int $quantity): void
    {
        $this->orderLines->push([
            'product_id' => $productId,
            'quantity' => $quantity,
        ]);
    }
}

In this component a user can add orderlines to the order. However we want to make sure that the user does not accidentally add a product twice.

To do this we can use the array validation features Laravel provides:

public function save(): void
{
    $validatedData = Validator::make([
        'orderLines' => $this->orderLines->toArray(),
    ], [
        'orderLines.*.product_id' => 'distinct',
        'orderLines.*.quantity' => 'required|integer|min:1',
    ]);

    // Do something with the validated data.
}

As you can see we can use the * to say we need to validate every item in the orderLines array. We use the distinct rule on the product_id to make sure every product_id is only selected once.

You can read more about array validation in Laravel in the documentation: Validating Arrays.