I can not see anywhere we can validate array index with default Laravel validation. That why we need to write a custom one.
public function rules()
{
$rules = [
'quantity.*' => 'required|integer|min:1',
'quantity' => [
'required',
'min:1', // make sure the input array is not empty <= edited
'array',
function($attribute, $value, $fail) {
// index arr
$ids = array_keys($value);
// query to check if array keys is not valid
$stockCntWithinArrIDs = StockModelFullNameWhaterver::whereIn('id', $ids)->count();
if ($stockCntWithinArrIDs != count($ids))
return $fail($attribute.' is invalid.'); // -> "quantity is invalid"
}
],
];
return $rules;
}
The main point is compare stock count result when query whereIn
(to reduce cost) their id with the array_keys of quantity
. Because quantity
's index is exists in stocks
, $stockCntWithinArrIDs
has to equal to count($ids)
, if not, there is at least one index is not as stocks
id.
You can use foreach ($ids)
then query the corresponding stock
to see if my solution work. But PLEASE DO NOT use that solution on production env. :D
Hope this help!
Edited:
See: https://laravel.com/docs/5.6/validation#custom-validation-rules