Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

makapaka's avatar

How to validate both the key and value of a request array

Can anyone suggest how to do the following.

I have a request body

{
    "sell": {
         "111": [1 , 2 , 3]
       }
 }

I need to validate 111 as an id on one table, and 1, 2, 3 as ids that exist on a different table.

What is the format for this ?

'sell' => 'required|sell|exists:stock,id',
'sell' => 'required|sell|exists:exchange,id'

Ie, table stock should contain ids of 1, 2, 3; table exchange should contain id 111 - which is also FK exchange_id in stock table.

That's not right is it, how do I indicate validation for both the key and values of the sell element ? Hope this makes sense

thanks

0 likes
3 replies
bobbybouwmann's avatar

I think you can do something like this

$rules = [
    'sell.*' => 'required|sell|exists:stock,id',
    'sell.*.*' => 'required|sell|exists:exchange,id',
]);

Note: I didn't tested this at all!

Another solution would be structuring the data a bit differently.

{
    "sell": {
        "111":[
            {"id": 1},
            {"id": 2},
            {"id": 3}
        ]
    }
 }

I believe you can then do this in your validation

$rules = [
    'sell.*' => 'required|sell|exists:stock,id',
    'sell.*.id' => 'required|sell|exists:exchange,id',
]);

Documentation: https://laravel.com/docs/5.8/validation#validating-arrays

If this isn't working I would probably make my own custom validation rule to validate this really specific case!

makapaka's avatar

thank you @bobbybouwmann

I am trying first method for just the first key validation and getting validator error: BadMethodCallException: Method [validateSell] does not exist... Validator.php

I'm using it in Rules class

$rules = [ 'sell.*' => 'required|sell|exists:stock,id' ]

and in controller calling it

$this->validate($request, $this->tradeRules->getRules($request));

Any thoughts - there is no validateSell method I have to explicitly create ?

I'm assuming the validation string required|<request element>|exists: <table>, <field> ?

Please or to participate in this conversation.