Laravel Remove/Trim Empty & Whitespace From Input Requests

Published on March 20, 2020 29 sec read

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:


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.

protected $middleware = [

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

That’s all. Thank you. 🙂

Monthly Newsletter

One email a month, packed with the latest tutorials, delivered straight to your inbox.
We'll never send any spam or promotional emails.

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