A
A
alexkst2021-10-18 11:20:33
Laravel
alexkst, 2021-10-18 11:20:33

How to make validation in Laravel for dynamic form?

I have an array of objects, a rather large JSON, in which the validation type of each object is determined through the "type" parameter. How can all this be put into a FormRequest, if there can be an unlimited number of validation types, and the rules are stored in the database?

Array example:

[
    {
        type: "link", 
        url: "https://link.com", 
      ...
    }, 
    {
        type: "image", 
        id: "drre-ggre-765", 
        image: "url"
        ...
     },
     {
         type: "arrayOfLinks", 
         links: [
             {
                  link: "www.www",
                  title: "Title"
             }
             ...
         ]
     }
     ...
]

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Ukolov, 2021-10-18
@alexkst

In the rules() method, you can get all the passed data. You can then iterate over them and add the necessary rule to the $rules array, depending on the type:

$rules = [...];

foreach ($this->get('some-field') as $index => $item) {
  switch ($item['type']) {
    case 'some-type':
      $rules["some-field.{$index}"] = [
        'some-rule',
      ]
      break;
  }
}

return $rules;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question