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.

2
  • What version of Laravel are you using? Commented Jun 5, 2018 at 8:00
  • @Ross Laravel 5.6 Commented Jun 5, 2018 at 8:09

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

2 Comments

thanks, your solution ready for production env ? (just curious)
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. :D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.