Home > Enterprise >  How to pair two arrays input validation in Laravel?
How to pair two arrays input validation in Laravel?

Time:01-13

I have a form request with rules

return [
    'brand_id' => ['required', 'integer'],
    'color_id' => ['required', 'integer'],
    'name' => ['required', 'max:255', 'string'],
    'capital' => ['required', 'string'],
    'price' => ['required', 'string'],
    'size' => ['required', 'string', 'max:255'],
    'incoming.*' => ['required', 'integer', 'gte:outgoing.0'],
];

I want to pair the validation by its each index, it is possible to do that in Laravel?

I ended up with this way

foreach ($this->incoming as $key => $value) {
    $incoming["incoming.{$key}"] = ['required', 'integer', "gte:outgoing.{$key}"];
}

return array_merge([
    'brand_id' => ['required', 'integer'],
    'color_id' => ['required', 'integer'],
    'name' => ['required', 'max:255', 'string'],
    'capital' => ['required', 'string'],
    'price' => ['required', 'string'],
    'size' => ['required', 'string', 'max:255'],
], $incoming);

CodePudding user response:

I would suggest a bit more elegant way:

return array_merge(
  [
    'brand_id' => ['required', 'integer'],
    'color_id' => ['required', 'integer'],
    'name' => ['required', 'max:255', 'string'],
    'capital' => ['required', 'string'],
    'price' => ['required', 'string'],
    'size' => ['required', 'string', 'max:255'],
  ],
  ...array_map(
    fn ($key) => ["incoming.{$key}" => ['required', 'integer', "gte:outgoing.{$key}"]],
    array_keys($this->incoming),
  )
);
  • Related