Search code examples
laravelvalidation

Laravel - Access information with nested validation request


I want to access information within nested validation array to do a custom validation, here is my code:

return [
...,
'amount' => ['nullable', 'numeric'],
'currency_id' => ['nullable', 'integer', Rule::in($allowedCurrencyIds)],
'details' => ['nullable'],
'details.*.product_id' => ['required', 'integer', 'exists:products,id'],
'details.*.product_collection_id' => [
   'nullable',
   'integer',
   'exists:product_collections,id',
   new ProductAndCollectionValidator($this->details.*.->product_id, $this->details->product_collection_id)
],
...
]

As you can see I want to access the product id and the product collection id with details.* to send to the custom validatior ProductAndCollectionValidator. And I need to concider that product_collection_id might be null sometimes. And that is the first step.

Second step I want to make sure that there are no duplicate product_id and product_collection_id the the details array

How can I do that?


Solution

  • you can use Laravel's custom validation rules and validation closures. https://laravel.com/docs/11.x/validation#using-closures. Try this on your validator:

    return [
        // Other validation rules...
        'details.*.product_id' => ['required', 'integer', 'exists:products,id'],
        'details.*.product_collection_id' => [
            'nullable',
            'integer',
            'exists:product_collections,id',
            function ($attribute, $value, $fail) {
                // Accessing nested values within details array
                $productId = $this->input('details')[$this->getIndexFromAttribute($attribute)]['product_id'];
                // Custom validation logic using ProductAndCollectionValidator
                $validator = new ProductAndCollectionValidator($productId, $value);
                if (!$validator->passes()) {
                    $fail($validator->message());
                }
            }
        ],
        'details' => ['nullable', function ($attribute, $value, $fail) {
            // Custom validation rule to check for duplicates
            $uniqueDetails = collect($value)->unique(function ($detail) {
                return $detail['product_id'] . '-' . $detail['product_collection_id'];
            });
            if ($uniqueDetails->count() !== count($value)) {
                $fail('Duplicate product_id and product_collection_id combinations found.');
            }
        }],
    ];
    
    
    function getIndexFromAttribute($attribute)
    {
        return explode('.', str_replace(['[*]', '*'], ['.', ''], $attribute))[1];
    }
    

    Let me know. Cheers.