- Notifications
You must be signed in to change notification settings - Fork 11.6k
Description
- Laravel Version: 9.23.0
- PHP Version: 8.1.9
- Database Driver & Version: X
Description:
After route:cache, Route::current()->getPrefix() returns the current route prefix without slash at the start.
I think it would be better to unify this and always return prefix without slash at the start.
Not Cached
Route::current()->getPrefix() returns "/testPrefix";
Cached
Route::current()->getPrefix() returns "testPrefix";
This only happens for grouped routes:
// Broken, getPrefix() returns -> NOT CACHED: "/test" | CACHED: "test" Route::prefix("/test")->group(function () { Route::view("/", "pages.test")->name("test"); }); // Broken, getPrefix() returns -> NOT CACHED: "/test" | CACHED: "test" Route::group(["prefix" => "/test"], function () { Route::view("/", "pages.test")->name("test"); }); // Broken, getPrefix() returns -> NOT CACHED: "/test" | CACHED: "test" Route::controller(TestController::class)->prefix("/test")->group(function () { Route::view("/", "pages.test")->name("test"); }); // Working as expected, getPrefix() returns -> NOT CACHED: "test" | CACHED: "test" Route::view("/", "pages.test")->prefix("/test")->name("test");I think the problem is in the RouteGroup::formatPrefix() method.
framework/src/Illuminate/Routing/RouteGroup.php
Lines 64 to 73 in 2a1a55c
| protected static function formatPrefix($new, $old, $prependExistingPrefix = true) | |
| { | |
| $old = $old['prefix'] ?? ''; | |
| if ($prependExistingPrefix) { | |
| return isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old; | |
| } else { | |
| return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old; | |
| } | |
| } |
Here if the old prefix isnt set it basically does this - "" . "/" . "newPrefix" -> adds slash at the start because the old prefix is an empty string.
I managed to fixed the problem by adding ltrim to the return.
$old = $old['prefix'] ?? ''; if ($prependExistingPrefix) { return ltrim(isset($new['prefix']) ? trim($old, '/').'/'.trim($new['prefix'], '/') : $old, '/'); } else { return isset($new['prefix']) ? trim($new['prefix'], '/').'/'.trim($old, '/') : $old; }If my understanding of the problem is correct, I would be happy to submit a PR to fix this.
#43376 # Steps To Reproduce: