laravel how to validate array index and values
Asked Answered
T

1

5

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.

Thrombin answered 5/6, 2018 at 7:14 Comment(2)
What version of Laravel are you using?Warranty
@Ross Laravel 5.6Thrombin
L
11

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

Lout answered 5/6, 2018 at 8:12 Comment(2)
thanks, your solution ready for production env ? (just curious)Thrombin
Actually, 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. :DLout

© 2022 - 2024 — McMap. All rights reserved.