Validate Your App on the Frontend With Laravel Dry Run Requests

Packages

June 23rd, 2022

laravel-dry-requests-featured-1655843438.png

The Laravel Dry Requests package checks if your requests would pass validation if you executed them normally. Think of it as the equivalent of a --dry-run CLI flag for request validation. Using this package, you can hit the endpoint users are using to enter a form and get real-time feedback with 100% validation accuracy:

The way it works under the hood is that it runs validation logic for a controller but skips the controller action. This package returns a 200 OK status response when given an X-Dry-Run: true header. Fields not present get omitted dynamically using the sometimes rule to ensure good UX.

You can start using this validation package by either adding a DryRunnable trait to a form request or using $request->validate() directly:

1class StoreUserRequest extends FormRequest
2{
3 use DryRunnable;
4 
5 public function rules(): array
6 {
7 return [
8 'email' => ['required', 'email', 'max:255', 'unique:users'],
9 'username' => ['required', 'string', 'min:2', 'max:255', 'unique:users'],
10 'nickname' => ['nullable', 'string', 'min:2', 'max:255'],
11 ];
12 }
13}

On the frontend, you need to send the X-Dry-Run header to validate form input before submitting the whole form:

1// 1. "Username is unavailable" validation error
2axios.post(
3 '/users',
4 { username: 'Agent007' },
5 { headers: { 'X-Dry-Run': true } }
6 )
7 .then(response => response.status);

To learn more about all the features in this package, including Inertia.js support and advanced features, check out the laravel-dry-requests package on GitHub.

Filed in:

Paul Redmond

Full stack web developer. Author of Lumen Programming Guide and Docker for PHP Developers.

Laravel News Partners