xinningsu / laravel-route-trailing-slash
Let laravel route work as exactly as how we define it including the trailing slash.
Requires
- php: >=5.6
- laravel/framework: >=5.4
Requires (Dev)
- php-coveralls/php-coveralls: ^2.1
- phpunit/phpunit: >=5.0
- squizlabs/php_codesniffer: ^3.0
This package is auto-updated.
Last update: 2024-11-18 20:41:37 UTC
README
Let laravel route work as exactly as how we define it including the trailing slash.
Background
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.
Define a route like this
use App\Http\Controllers\PartnersController; Route::get('/partners/', [PartnersController::class, 'index'])->name('partners');
Output the route url
echo route('partners');
Current behavior
https://laravel.com/partners
Expected behavior
https://laravel.com/partners/
Pagination render
Using database query builder or LengthAwarePaginator/Paginator
Current behavior
https://laravel.com/partners?page=2
Expected behavior
https://laravel.com/partners/?page=2
Installation
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.
RoutingServiceProvider
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);
PaginationServiceProvider
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.
Mismatch action
Currently Laravel will trim trailing slashes of access url, so no matter how many trailing slashes the url has, it makes no difference.
Current behavior
Now we can custom the mismatch action, such as abort 404, or 301/302 redirect, if route mismatch only because of trailing slash.
404 action
open app/Providers/AppServiceProvider.php
, add below line to register
method
\Sulao\LRTS\Routing\Router::$mismatchAction = 404;
Now the behavior became
301/302 action
open app/Providers/AppServiceProvider.php
, add below line to register
method
\Sulao\LRTS\Routing\Router::$mismatchAction = 301;
Now the behavior became