Photo by Shirly Niv Marton on Unsplash

Testing Laravel Form Requests in a different way

Daan
6 min readApr 16, 2019

--

Many developers are struggling with testing form requests in an efficient way. Most of the time you’ll end up with writing a seperate unit test for each rule that is defined in your form request. This results in a lot of tests like test_request_without_title and test_request_without_content. All of these methods are implemented in exactly the same way, only calling your endpoint with some different data. This will result in a lot of duplicate code. In this guide I will show you a different way to test your form request, which I think is more clean and improves the maintainability of your tests.

Creating a form request

For this example I will be making a form request to save a product.

php artisan make:request SaveProductRequest

The generated file class will be placed in App/Http/Requests.

We will declare a set of validation rules for this form request:

  1. The title parameter should be a string with a maximum of 50 characters.
  2. The price parameter should be numeric.

Those are the only two validation rules for now.

This is what the SaveProductRequest class looks like:

<?php

namespace App\Http\Requests;

use…

--

--