Search code examples
phplaravellaravel-5laravel-validation

laravel how to validate array index and values


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.


Solution

  • 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