Laravel Remove/Trim Empty & Whitespace From Input Requests

Published on March 20, 2020 29 sec read

HIRE US 🖐
We're available to do freelance project. Take a look at our services!

In this article, we’re going to learn how to remove/trim empty and whitespace from all input requests in Laravel.

Table of Contents

  1. Create Middleware
  2. Update Kernel

Create Middleware

We’ll remove empty spaces using Laravel middleware. Let’s create a middleware named SpaceRemover:

php artisan make:middleware SpaceRemover

Open the middleware SpaceRemover.php from app/Http/Middleware folder and paste this code:

SpaceRemover.php
<?php

namespace App\Http\Middleware;

use Closure;

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

Update Kernel

Open the Kernel.php from app/Http folder and add our newly created middleware to the $middleware array.

Kernel.php
protected $middleware = [
    //--------------
    \App\Http\Middleware\SpaceRemover::class,
];

Now our application will remove all empty spaces. You can pass empty space and test.

That’s all. Thank you. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write on Laravel, Linux server, modern JavaScript and more on web development.

Follow

Leave a Reply

Your email address will not be published. Required fields are marked *