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.

app/Http/Middleware/RemoveTrailingSlashMiddleware.php
<?php

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!

Bobby Bouwmann and I are writing a book called "Laravel Secrets".
You will learn everything about the undocumented secrets of the popular Laravel framework. You can sign up using the form below to get early updates.
      Visit laravelsecrets.com to get more information.