Automatically trim request input

Snippet published on December 3, 2016 by @markvaneijk in Laravel

Using a middleware we can automatically trim input from the request in your Laravel app. To make it even more useful we can automatically set empty values to null so it will be saved to your database as NULL. Clean and simple!

<?php

namespace App\Middleware;

use Closure;

class TrimInput
{
    public function handle($request, Closure $next)
    {
        $input = $request->all();

        array_walk_recursive($input, function (&$value) {
            $value = trim($value) ?: null;
        });

        $request->merge($input);

        return $next($request);
    }
}