Let laravel route work as exactly as how we define it including the trailing slash.
Currently when we define a route, Laravel will trim all the trailing slashes, output the route url without any trailing slash. When we access an url with trailing slashes, Laravel also will trim them. That makes the trailing slashes meaningless, sometimes it's quite annoying.
use App\Http\Controllers\PartnersController;
Route::get('/partners/', [PartnersController::class, 'index'])->name('partners');
echo route('partners');
https://laravel.com/partners
https://laravel.com/partners/
Using database query builder or LengthAwarePaginator/Paginator
https://laravel.com/partners?page=2
https://laravel.com/partners/?page=2
composer require xinningsu/laravel-route-trailing-slash
There are two service providers, as the router service provider has to register at the very beginning before laravel http kernel class instantiation, so I can not make it work by Laravel Package Auto-Discovery function. Have to manually add it.
open bootstrap/app.php
, right after app instantiation
$app = new Illuminate\Foundation\Application(
$_ENV['APP_BASE_PATH'] ?? dirname(__DIR__)
);
add
$app->register(Sulao\LRTS\Routing\RoutingServiceProvider::class);
Pagination Service Provider has to be added after laravel original Pagination Service Provider.
add Sulao\LRTS\Pagination\PaginationServiceProvider::class
to config/app.php under providers
element, after Illuminate\Pagination\PaginationServiceProvider::class
[
Illuminate\Pagination\PaginationServiceProvider::class,
// ...
/*
* Package Service Providers...
*/
Sulao\LRTS\Pagination\PaginationServiceProvider::class,
// ...
];
That's it, now we can generate url with/without trailing slash, same as the definition of route.
Currently Laravel will trim trailing slashes of access url, so no matter how many trailing slashes the url has, it makes no difference.
URL | Status |
---|---|
https://laravel.com/partners | 200 |
https://laravel.com/partners/ | 200 |
https://laravel.com/partners//// | 200 |
Now we can custom the mismatch action, such as abort 404, or 301/302 redirect, if route mismatch only because of trailing slash.
open app/Providers/AppServiceProvider.php
, add below line to register
method
\Sulao\LRTS\Routing\Router::$mismatchAction = 404;
Now the behavior became
URL | Status |
---|---|
https://laravel.com/partners | 404 |
https://laravel.com/partners/ | 200 |
https://laravel.com/partners//// | 404 |
open app/Providers/AppServiceProvider.php
, add below line to register
method
\Sulao\LRTS\Routing\Router::$mismatchAction = 301;
Now the behavior became
URL | Status |
---|---|
https://laravel.com/partners | 301 redirect to https://laravel.com/partners/ |
https://laravel.com/partners/ | 200 |
https://laravel.com/partners//// | 301 redirect to https://laravel.com/partners/ |