S
S
Sergey delphinpro2021-08-21 13:37:19
Laravel
Sergey delphinpro, 2021-08-21 13:37:19

How to write validation?

I have a big form. The data from this form is stored in two tables. Part to one, part to another.
I see options:
One common validator. Then scatter each field according to the models

$validator = Validator::make();
$validator1->validate();
//...
$model1->update([
  'field1_1' => $request->get('field1_1'),
  // Дофига полей
]);
$model2->create([
  'field2_1' => $request->get('field2_1'),
  // Дофига полей
])


Or write two validators and shorten the second part.

$validator1 = Validator::make();
$validator2 = Validator::make();

$data1 = $validator1->validate();
$data2 = $validator2->validate();

$model1->update($data1);
$model2->create($data2);


But here I run into the problem of catching validation errors. I write something like this, but I don't like it:

try {
  $data = $validator1->validate();
} catch (ValidationException $e) {
  return redirect()->back()->withErrors($validator1)->withInput();
}

try {
  $data = $validator2->validate();
} catch (ValidationException $e) {
  return redirect()->back()->withErrors($validator2)->withInput();
}


What to do? Maybe somehow two validators can be combined? Or is there some other way to describe it? Or leave the first option, albeit a little more verbose?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
J
jazzus, 2021-08-21
@delphinpro

one request one request file. in it, validation of all fields, then in the controller you do what you need with them. and Laravel itself will return errors

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question