1

I have an items array, sent to the controller as JSON within the items form key.

[{
    "sku": "w-hook-as1",
    "qty": 2,
    "cost_ex_tax": "34.22",
    "tax_rate": "0.2"
}]

Here it is converted to an array:

$request->merge(['items' => json_decode($request->items, true)]);

and validated against the rule:

'items.*.sku' =>[
    'required',
    Rule::exists('products')->where(function ($query) {
        $query->where('company_id', Auth::user()->company_id);
    })
],

The exists rule does work, if the array key that its validation against exists, assuming the key exists. If I simply send:

[{
    "qty": 2,
    "cost_ex_tax": "34.22",
    "tax_rate": "0.2"
}]

Then the validation passes.

Is there a way I can check that the key exists as well as validate its content? I would have expected that the required check does this, but it does not seem to work.

How to validate array in Laravel? - This answer suggests to validate that it is an array with x number of elements, but still does not check the exact keys I am looking for are there.

Adam Lambert
  • 1,311
  • 3
  • 24
  • 45

1 Answers1

0

I tried to replicate what you have without the custom Rule so what I did is the following:

in my blade I have

<input type="text" name="items" value='[{"sku": "w-hook-as1","qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}, {"qty": 2,"cost_ex_tax": "34.22","tax_rate": "0.2"}]'>

You can notice here that in my second object I don't have the sku item in the object. Then in the controller:

$arr = request()->merge(['items' => json_decode(request('items'), true)]);

$validator = Validator::make($arr->all(), [
   'items.*.sku' =>[
        'required'
    ]
]);

dd($validator->fails(), $validator);

And the response is the following:

true // this is because the validation fails.
// and the message bag contains this
#messages: array:1 [▼
  "items.1.sku" => array:1 [▼
    0 => "The items.1.sku field is required."
  ]
]

So make sure you are not doing anything wrong.

Print out $request->all() and make sure that your items have the following content:

"items" => array:2 [▼
  0 => array:4 [▼
    "sku" => "w-hook-as1"
    "qty" => 2
    "cost_ex_tax" => "34.22"
    "tax_rate" => "0.2"
  ]
  1 => array:3 [▼
    "qty" => 2
    "cost_ex_tax" => "34.22"
    "tax_rate" => "0.2"
  ]
]

if not then you need to modify your validation.

Let me know if I am not following some steps that you do.

nakov
  • 13,938
  • 12
  • 60
  • 110