Laravel middleware to remove/trim empty whitespace from the input request

In this Laravel PHP Tutorial, we will let you know how to create custom middleware to remove/delete whitespace from the string in the request.

Laravel is a great framework that provides a variety of tools and inbuilt functions to tackle almost everything we need to create a good web application.

Whitespace is any string of text composed only of spaces, tabs, or line breaks. These characters allow you to format your code in a way that will make it easily readable by yourself and other people. But in programming when we are working array then whitespace can affect your code logic, so it’s always a good idea to trim the whitespace from the incoming request. Because users can’t be trusted in the programming so we need to protect our code as much as possible.

Sometimes user searches for empty strings and gets empty results because empty strings behave like characters which are accurate but this is not the good practice to send user input data directly into the query without sanitizing input data. So we always recommend sanitizing the data before processing in the logic.

You can trim all input using the custom middleware in Laravel. So let’s make a custom middleware for removing and trimming blank or white space from the input string.

Create Middleware

You can use the PHP artisan command to create the middleware file to trim request data.

php artisan make:middleware BeforeAutoTrimmer

Update the below code in the newly created middleware file (located at app/Http/Middleware/BeforeAutoTrimmer.php).

<?php 
namespace App\Http\Middleware;
use Closure;

class BeforeAutoTrimmer {
    
    public function handle($request, Closure $next)
    {
        $request->merge(array_map('trim', $request->all()));
        return $next($request);
    }
}

Update the Laravel Kernel file

Once you have done with your middleware file, you need to tell the Laravel application to run middleware on each request or you can apply it for a specific group to trim whitespace from the request data.

app/Http/Kernel.php:

protected $middleware = [
        // ..
        \App\Http\Middleware\BeforeAutoTrimmer::class,
    ];

Recommended Posts For You

Spread the love