0

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);
2
  • Have you tried to use * with outgoing like this: 'incoming.*' => ['required', 'integer', 'gte:outgoing.*'], ? Commented Jan 12, 2023 at 12:58
  • I don't think it will work since he wants to compare the two values with the same key. and if he use the * it will compare to all values. Commented Jan 12, 2023 at 14:16

1 Answer 1

0

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),
  )
);
Sign up to request clarification or add additional context in comments.

Comments

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.