laravel how to validate array index and values
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
Joyal
Updated on June 12, 2022Comments
-
Joyal almost 2 years
I am submitting a single dimensional array of values to process on laravel 5.6
quantity[4]:11 quantity[2]:14
I have to validate both the index and the value, index should exits as stocks,id and value must be integer and minimum 1
I tried
public function rules() { $rules = [ 'quantity.*' => 'exists:stocks,id', 'quantity' => 'required|integer|min:1', ]; return $rules; }
but its validating only the values not index, please share your thoughts and comments.
-
Joyal almost 6 yearsthanks, your solution ready for production env ? (just curious)
-
vietanhyt almost 6 yearsActually, I've never seen input like that, I mean array indexes are existed in a table, so, the answer is no. But I wrote a lot of custom rules in my projects before. And I believe it can be used. :D