Search code examples
phplaravel-8laravel-backpack

How add a request rule to Backpack-Laravel?


I need to dynamically assemble request rules depending on the value of a model field. I have a model author with a field string $rule. This field can store string values ​​for the request - integer, string, boolean etc.

Create crud model

protected function setupCreateOperation()
{
     $this->crud->setValidation(AutorCreateRequest::class);
     $this->crud->addFields(...);
}

Getting the value of the type field in the current model inside AuthorCreateRequest failed - this is normal. This class knows nothing about the current model. So I need to add dynamic rules to the current ones somewhere inside the setupCreateOperation method. How do I do this?

For example

protected function setupCreateOperation()
{
    // AutorCreateRequest with default rule
    $this->crud->setValidation(AutorCreateRequest::class);
    $this->crud->addFields(...);

    // I would like to see something like this
    // add new rules to default rules 
    $this->crud->request->rule->add([
        'value' => [
              'required',
              $type
        ]
    ]);
}

Solution

  • You can dynamically customize the rules array within your request class AutorCreateRequest:class

    I do it within the rules() function. In my case, I customize the array on the basis of some setting or request().