Physical Address

304 North Cardinal St.
Dorchester Center, MA 02124

trailing slash in every routes in laravel

How to append a trailing slash in every route in Laravel 8?

In this tutorial, I will give you an example of “How to append a trailing slash in every route in Laravel”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.

First, what we’re doing here, This is the example :

Laravel - append a trailing slash in every routes

trailing slash after every url laravel

Adding trailing slash after every URL in Laravel

Adding a trailing slash to a URL is unnecessary most of the time but comes to use in cases where we are working on a website that has been online for a couple of years and all the URLs in the past used to be with a trailing slash and it depends on client requirements or SEO purpose.

Laravel applications have also included its .htacess file, where you can add a block of code for redirection and add a trailing slash to all URLs. It is very risky to edit in a .htaccess file, so we will do it with the help of Middleware.

Append a trailing slash in every route using Middleware

Middleware that checks the URI request for the presence of a trailing slash at the end. If the trailing slash is not present in the URI, then, it will append a trailing slash, Let’s see how to append a trailing slash in every route in Laravel.

Create a Middleware

php artisan make:middleware TrailingSlashes
Laravel - append a trailing slash in every routes using middleware

app\Http\Middleware\TrailingSlashes.php

<?php
namespace App\Http\Middleware;

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


class TrailingSlashes
{
  /**
  * Handle an incoming request.
  *
  * @param  \Illuminate\Http\Request  $request
  * @param  \Closure  $next
  * @return mixed
  */
  public function handle($request, Closure $next)
  {
    if (!preg_match('/.+\/$/', $request->getRequestUri()))
    {
      $base_url = 'http://127.0.0.1:8000';
      return Redirect::to($base_url.$request->getRequestUri().'/');
    }
    return $next($request);
  }
}

When you are working on a local server put your local server URL like: http://127.0.0.1:8000, and when you are working on a live domain server change your base URL like: www.yourdomain.com.

Update Kernel File :

You need to update your Kernel.php file inside the same App/Http/Middleware directory where you need to add the middleware name as shown below.

app\Http\Kernal.php

protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
        'authCheck' => \App\Http\Middleware\AuthCheck::class,
        'slashes' => \App\Http\Middleware\TrailingSlashes::class,
    ];

Http\Controllers\TestController.php :

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Category;

class TestController extends Controller
{
    public function addcategory()
    {
        return view('category.add');
    }

    public function listcategory()
    {
        $category = Category::get();
        return view('category.list',compact('category'));
    }
}

When you have only a single route :

If you want to add a trailing slash only in a few URLs, just add middleware after route name in the route file.

Route::get('/category-list', [TestController::class, 'listcategory'])->name('cat.list')->middleware('slashes'); 
How to append a trailing slash in every route in Laravel 8?

When you have multiple routes Group :

If you want to add a trailing slash in all URLs, just create a route group and place all the routes into the middleware group in the route file.

Route::group(['middleware' => 'slashes'], function()
{
Route::get('/add-category', [TestController::class, 'addcategory'])->name('cat.add');
Route::get('/category-list', [TestController::class, 'listcategory'])->name('cat.list'); 
});
trailing slash in every routes in Laravel
trailing slash in every routes in Laravel

Also Read : Display Session Flash Message in Laravel 8.