DRY Create And Update Laravel Form Requests

In this tutorial we're going to investigate how we can reuse the logic in Laravel Form requests for the difference between Create and Update requests. Laravel form requests are great, they allow you to include all the validation and authentication logic in the request object and you will know everything in the controller has already been validated. To learn more about validation in Laravel you can read a previous article about Laravel validation requests. The problems you can come across when building an app is dealing with the same request but for different actions such as Create and Update requests. The majority of the data types will be the same but with updates you might be passing in new data you can edit.

Create Post


class CreatePost extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|string',
            'content' => 'required|string'
        ];
    }
}

Update Post


class UpdatePost extends FormRequest
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return [
            'title' => 'required|string',
            'content' => 'required|string',
            'status' => 'integer|in:0,1,2'
        ];
    }
}

DRY Requests

As you can see from the code above the two request objects are very similar apart from one extra field on the UpdatePost request so let's see how we can DRY these classes. As the UpdatePost request is the same as the CreatePost but with an extra field, why not just reuse the CreatePost request rules. We do this by extending the CreatePost, then perform an array_merge on the CreatePost object from the UpdatePost object and then add any new rules we wish.


class UpdatePost extends CreatePost
{
    /**
     * Get the validation rules that apply to the request.
     *
     * @return array
     */
    public function rules()
    {
        return array_merge(parent::rules(), [
            'status' => 'required|integer|in:0,1,2',
        ]);
    }
}

UpChecker

Reliable uptime monitoring and instant alerts for any website downtime.

  • Uptime Monitoring
  • Performance Monitoring
  • SSL Certificate Alerts
  • Domain Monitoring
  • DNS Checker
  • XML Sitemap Monitoring