Laravel Remove Empty Spaces From Input Requests

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.