January 26, 2017 • 1 minute read
Using Laravel 5.4 Request Sanitization Middleware
One of the new features introduced in Laravel 5.4 is a pair of middleware for sanitising data in requests. These middleware are:
TrimStrings
ConvertEmptyStringsToNull
Both of these middleware are very useful. TrimStrings
will trim whitespace surrounding any request input values. ConvertEmptyStringsToNull
will take any inputs that have been submitted with no value and convert them from an empty text string ''
to null
.
The latter is very useful when you want to ensure that any empty fields are stored in your database as NULL
and not empty strings. By doing this at a middleware level, you can ensure your application handles this consistently across the board.
In the past, you may have written something like the following when saving data following a form submit:
$post->published_at = request()->published_at ?: null;
With this new middleware, you no longer need the ?: null
bit.
At the time of writing, the guidelines on using these middleware in the Laravel 5.4 release notes doesn’t work when upgrading a Laravel 5.3 application. To use the middleware, you need to add the following lines to the $middleware
array in your app\Http\Kernel.php
file:
\Illuminate\Foundation\Http\Middleware\TrimStrings::class,
\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
One small problem you might run into when you enable the ConvertEmptyStringsToNull
middleware is with form validation. If you have validation rules that check the format of a field (such as using the date
rule to check for valid dates), but that field is not required, you’ll find that the validation will fail when the field is empty. To fix this, you need to ensure that you add the nullable
rule to the field. For example:
public function rules()
{
return [
'title' => 'required',
'published_at' => 'nullable|date',
'image_url' => 'nullable|url',
];
}
Now your validation rules will work as expected.