'Laravel validate a quantity field in an array of arrays

selected_products is an array of arrays

^ array:7 [▼
  "selected_products" => array:2 [▼
    0 => array:2 [▼
      "id" => 2
      "quantity" => 10
    ]
    1 => array:2 [▼
      "id" => 1
      "quantity" => 22
    ]
  ]
]

I'm trying to validate the quantity of each product if greater than or equal to the quantity in stock I want to get a Out of stock error

Product and Stock is a one to one relationship

Product.php

public function stock () {
    return $this->morphOne(Stock::class, 'stockable');
}

This is what I tried so far

StoreActivityRequest.php

'selected_products.*.quantity' => [function ($input, $item) {
    return $item > Product::find($input->id)->stock->quantity;
}]

I'm kind lost here



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source