'Trailing slash lead to miss route parameter

First of all, I have route in my routes/web.php file (I commented all other routes during long time experimented):

Route::get("someprefix/{slug}", [SomeController::class,'index'])->name("someprefix.page")->where('slug', 'foo|bar');

My RouteServiceProvider looks pretty standard:

..
public function map(): void
{
    ..
    $this->mapWebRoutes();
}

protected function mapWebRoutes()
{
    ..
    Route::middleware('web')
        ->namespace($this->namespace)
        ->group(base_path('routes/web.php'));
    ..
}

Also I have controller with action:

class SomeController extends WebControllerAbstract
{
    public function index($slug = null)
    {
        // Here we will also try to get slug directly from route
        $slugFromRequest = request()->route()->parameter('slug');

        dump($slug);
        dd($slugFromRequest);

        $view = $this->view("$slug.index");
        return $view;
    }
}

Next, using artisan to build route cache:

artisan.sh route:cache

Artisan.sh route:list shows me proper list of routes. Everything all allright. But..

When I request /someprefix/foo the result is "foo""foo"

When I request /someprefix/foo/ the result is "null""null"

It looks like trailing slash lead to missing route parameter. Any ideas, what can be wrong?
I really tired to fight with it..



Solution 1:[1]

I created your example with clean Laravel 9 installation:

web.php

<?php

use App\Http\Controllers\TestController;
use Illuminate\Support\Facades\Route;


Route::get("/tests/{slug}", [TestController::class,'show'])->name("someprefix.page")->where('slug', 'foo|bar');

TestController@show

public function show($slug = null)
{
    $slugFromRequest = request()->route()->parameter('slug');

    dump($slug);
    dd($slugFromRequest);

    return $slug;
}

Test for it

public function test_a_send_slug_as_parameter()
{
    $this->get("tests/foo/")->assertOk();
}

Output: for both tests/foo and tests/foo/

"foo"
^ "foo"

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 gguney