3 months ago

Form Requests and Form Objects

In most cases, performing the persistence logic within the Controller is simple. In the cases where I need to perform additional tasks, muddying up the Controller with this logic can get a little messy. I want to clean this up, but how?

Form Objects.

Laravel already provides an easy to use interface for handling form requests in terms of validating the request data. I want to take this one step further, and turn my Form Requests into Form Objects. Form Objects will not only handle validating our request, but also be in charge of persisting the request to storage (e.g. the database).

To do this, I simply need to add a persist method:

<?php

namespace Modules\Test\Http\Forms;

class CreateTestForm extends FormRequest
{
    ...

    public function persist()
    {
        dump('perform necessary tasks and persist the data.');
    }

    ...
}

And within the controller, simply call it:

public function store(CreateTestForm $form)
{
    $form->persist();

    ...
}

Notes

One important thing to keep in mind with this approach, is to create a form object for each individual "form". This is important, because:

  1. Each form will have different validation rules.
  2. Each form will have different authorization rules.
  3. Each form will have different persistence logic - am I creating a new entry or updating an existing one?
  4. It keeps the controller and model clean!