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

gitwithravish's avatar

Dynamic request class injection in laravel

I have a custom request class which is getting longer and longer with project development.

An API endpoint is expected to have multiple types ofinput. Any one is expected to be received at once.

According to the input, the validation rules are being constructed.

Right now I am having a long list of swith-cases to construct validation rules.

I want to create multiple requests classes for each case and dynamically inject appropriate request class to the controller method. Note that I cannot create multiple api endpoints.

Is there any good suggestion to handle this?

0 likes
2 replies
Sinnbeck's avatar
Sinnbeck
Best Answer
Level 102

This sounds like what you are after. The example shows how the class is dynamically resolved :)

https://stackoverflow.com/a/34448047/1305117

/**
     * Get the sub class name with namespace
     * @return string
     */
    public function getRequestClass()
    {
        return '\<path>\<to\<namespace>\' . studly_case($this->resourceType) . 'Request';
    }
chuck_wood's avatar

Is it just me or does this seem like it's what dependency injection is supposed to be for?

Please or to participate in this conversation.