Can you "embed" a FormRequest object within another FormRequest object?

Posted 4 months ago by SteveMelrose

I recently upgraded an app of mine from 5.2 to 5.7 (side note, Shift is awesome). I'm now trying to refactor my app to more align with the "Laravel way". The area I'm looking at and having some "issues" with is FormRequest objects.

My app is a more or less standard CRUD GUI, nothing too complicated. My current way of doing things is actually very similar to FormRequest objects,

  • At the start of the POST controller handlers, I instantiate what I call an InputData object
  • I have unique versions of these objects for each request type, very similar to FormRequest objects. e.g. Attendee\StoreInputData (we don't have attendees, just an example)
  • Each object is responsible for,
    • Data sanitization, i.e. formatting data pre-validation
    • Defining validation rules
    • Executing validation and returning errors/clean data

All in all, these are more or less identical to FormRequest objects so migrating to them is pretty simple. Except this is where I start hitting a problem.

Our GUI is setup to allow "bulk" actions. For example, when creating a new Attendee you can also create at the same time in the same form a new Event (for example). With our way of doing things, we nest all the form fields in an add_event[] array in the POST data, and on the server we instantiate an Event\StoreInputData based on that array of data.

public function sanitize()

    if ($this->has('add_event')) {
        $this->set('add_event', new Event\StoreInputData($this->get('add_event')));
    } else {
        $this->set('add_event', null);

And then when you hit validate() on the Attendee\StoreInputData, it also validates any child InputData objects. This allows us to very easily share logic between different forms and embed forms/actions into other forms/actions.

So my question is, can I do this with FormRequest objects?

More specifically, can you effectively "embed" another FormRequest within a FormRequest for a single request? I know I could merge in the validation rules and sanitization rules form one to the other, but the fields won't match exactly and I would need to do some formatting, etc.

Is there a common or good way of doing this?


Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.