Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

nzmattman's avatar

Is it possible ro have dynamic form requests?1;?

Is it possible to have dynamic form requests?

I have a large project that will have a simple resourcefull controller setup (so simple crud setup).

I have about 30ish ‘modules’ that need this pattern.

I am thinking of extracting out all the controller methods to a trait, and set variables on the controller to control views and data etc.

I have the base methods done, but when it comes to store and update, i want to be able dynamically load a form request.

So something like this.

class FooController extends 
{
    use CrudTrait;

    protected $formRequest = FooRequest;
}

And the trait

…
public function store($this->formRequest $request)
{
…
}
0 likes
4 replies
nzmattman's avatar

@Harsha63 hi there. Thank you for your response. Not quite what im after I think.

The trait i want to be able to accept a form request that is set on the controller. Unless i read the links incorrectly, they all refer to having the form request on the controller, which im hoping to avoid.

The particular trait is to be used across at least 30 controllers, which will all have pretty similar base code. What really what im asking is if we can dynamically inject a different form request into the trait based on what controller is using it.

I may be able to get around it with using one base form request where i then go and pull in the correct form request based on the incoming route, but that seems a bit hacky

Snapey's avatar

@nzmattman You can have one common form request which you inject into each controller, then in the rules section, have the form request get the rules array from some central location according the type.

The thing with this though - and the reason to use a form request - is that the validation is performed before the controller is instantiated so you can't reach anything inside the controller. Within the form request you could inspect the route to know what set of rules to apply.

Once inside the controller, you can access the form request to save the data or whatever else you need it to do. (as I suggest here). https://talltips.novate.co.uk/laravel/simplify-laravel-crud-controllers#form-request

However you cut it, if you have 30 endpoints that all require form validations then you are going to have 30 sets of rules and validation messages. You are avoiding individual files for each form request, but not much else.

1 like
nzmattman's avatar

@Snapey thanks mate.

I have decided to go ahead and actually separate it out from the trait and actually have them in the controller, as I will need to inject the model as well, so just makes it easier to have it in the controller, saves on complication also.

Please or to participate in this conversation.