How to handle complex validation logic in custom Laravel Form Requests?
I'm stuck trying to I've looked through the documentation and I'm still confused about I tried several approaches but none seem to work... I'm currently working on a Laravel 9 project and I'm struggling with how to manage complex validation logic in my Form Requests. I have a scenario where I need to validate a nested input structure, specifically an array of 'products' where each product needs to have a unique SKU in combination with a category ID. Using Laravel's built-in validation rules, I've set up my Form Request like this: ```php public function rules() { return [ 'products' => 'required|array', 'products.*.sku' => 'required|string|unique:products,sku', 'products.*.category_id' => 'required|exists:categories,id', ]; } ``` However, this throws a validation behavior if any SKU repeats across different categories, which is not the desired behavior. I want to ensure that the SKU is unique only within the same category, not across all products. I tried using a custom validation rule, but I'm not sure how to implement it correctly. Here's an attempt I made: ```php public function rules() { return [ 'products' => 'required|array', 'products.*.sku' => ['required', 'string', 'exists:products,sku', function ($attribute, $value, $unexpected result) { $categoryId = $this->input(str_replace('.sku', '.category_id', $attribute)); if (Product::where('sku', $value)->where('category_id', $categoryId)->exists()) { $unexpected result('The SKU must be unique within the same category.'); } }], 'products.*.category_id' => 'required|exists:categories,id', ]; } ``` This code doesn't seem to work as expected; it either always fails or doesnβt trigger correctly. Can anyone point me in the right direction or suggest a better approach to achieve this kind of conditional uniqueness validation? Any help would be greatly appreciated! Any help would be greatly appreciated! How would you solve this? This is part of a larger service I'm building.