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
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.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.