Laravel 5.2 is already good at sanitizing input data received from GET and POST data, but it doesn’t remove excessive spacing at the beginning or end of the data. This is in particular useful since some mobile devices often leave a trailing space thanks to auto-correct. Luckily, this is easy to achieve using Custom Middleware.
Create Middleware
You can using the artisan make command to help in creating the middleware file we will be using to trim all input. This can be achieved by running the command (where InputTrim
is the name of the middleware):
php artisan make:middleware InputTrim
Trimming the Input
In the newly created middleware file (located at app/Http/Middleware/InputTrim.php
), you just need to add one line of code above return $next($request)
– see Line 18 of the below code:
Updating the Laravel Kernel
Once you have updated the middleware, you need to tell Laravel to run the middleware on every request (or for a particular group). To do this, you need to update the app/Http/Kernel.php
file.
To run the Middleware on all HTTP requests, add line 11 from the below code to the end of the $middleware
array:
Your Kernel.php
should look like the above example. In our version, we have removed other middleware and group settings.
Credit to @t202wes for a version that works with arrays.