Search code examples
laravellaravel-validation

Validate array items with wheres from items


Context

I have two Order Models which are: Order and OrderItem.

in OrderController I want to validate array of items. I checked Laravel array validation and found out that I can use something like this:

    $customer_id = Auth::guard('api')->user()->id;
    $validate = validator($request->all(), [
        'address_id'    => 'required|numeric|exists:addresses,id,customer_id,' . $customer_id,
        'items.*.product_id'=> 'required|numeric|exists:products,id',
    ]);

this is working for "static validation"


Goal

I want to add the following rule

'items.*.product_color_id'  => 'required|numeric|unique:order_items,product_color_id,NULL,id,product_size_id,' . $request->product_size_id . ',product_id,' . $request->product_id . '|exists:product_colors,id,product,' . $request->product_id,

the problem is how can I make $request->product_size_id changes for each iteration in items??


Note

I thought about making them two controller OrderController and OrderItemController it will work this way but in this way the client has to send multiple requests (one for creating an Order and one for each item)


Solution

  • I found it here. I had to write a for loop for it something like this:

    $validation = [];
    for ($i = 1; $i <= count($request->get('recipients')); $i++) {
        $validation[] = [
                'to.'.$i.'.email' => 'required|email',
                'to.'.$i.'.name' => 'required|string',
        ];
    }
    
    $this->validate($request, ['to' => 'required|array'] + $validation);
    

    in this way I can get $request[$i]->get('product_size_id')