A middleware for removing trailing slashes

Published on June 10th, 2019

What really cool about middleware is, you can put in really little pieces of code. In my case, I wanted to remove all the trailing slashes and redirect to the same URL without the trailing slash. Nothing easier than that.


namespace App\Http\Middlware;

use Closure;
use Illuminate\Support\Facades\Redirect;

class RemoveTrailingSlashMiddleware
    public function handle($request, Closure $next)
        if (preg_match('/.+\/$/', $request->getRequestUri())) {
            return Redirect::to(rtrim($request->getRequestUri(), '/'), 301);

        return $next($request);

Oh and don't forget to register that middleware!

If you enjoy my articles or you like what I'am talking and twittering about, you should sign up. I will show you everything I know.
I send e-mails very irregularly. Your data is safe with me.