Laravel 5.4 Includes Two New Middleware
Published on by Eric L. Barnes
Laravel 5.4 is scheduled to be released next week, and it already includes many great new features, but the team was able to sneak in two new Middleware offerings. These are TrimStrings
and ConvertEmptyStringsToNull
.
Trim Strings Middleware
Just as the name suggests, the Trim Strings middleware will automatically trim all the request data so you don’t have to worry about those situations where someone may inadvertently add extra spaces in your form fields.
As an example let’s say you have a newsletter signup which requires an email address. Previously, if someone entered an extra space it would end up like this:
dd(request('email'));// 'demo@example.org '
Now, by adding the TrimStrings middleware to App/Kernel.php:
protected $middleware = [ \Illuminate\Foundation\Http\Middleware\TrimStrings::class,
This would result in:
dd(request('email'));// 'demo@example.org'
Convert Empty Strings to Null
Paired with the Trim Strings, is a new ConvertEmptyStringsToNull
which works in basically the same way. A good example is a form with a not required field that maps to a nullable database column.
As an example, pretend you have a VAT field for users to enter their tax code.
<input type="text" name="vat" value="">
If you left it blank prior, it would return an empty string:
dd(request('vat'));// ''
With the ConvertEmptyStringsToNull
middleware this will now be null:
dd(request('vat'));// null
Be sure and check out the Laravel 5.4 page to see other new features coming to this release and also join the newsletter to not miss out on new posts.
Eric is the creator of Laravel News and has been covering Laravel since 2012.