Search code examples
laravellaravel-routingcsrf-tokenlaravel-11route-model-binding

Laravel route model binding in laravel 11 doesn’t work for routes in a customized route file


In my laravel 11 app I created a route file named admin.php to put my admin routes there. I configured admin.php in bootstrap app.php based on laravel’s documentation this way:

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__.'/../routes/api.php',
        apiPrefix: '',
        then: function () {
            Route::prefix('')
                ->group(base_path('routes/admin.php'));
        },
    )
    ->withMiddleware(function (Middleware $middleware) {
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->shouldRenderJsonWhen(fn() => true);
    })
    ->create();

It worked fine until I wanted to use Route Model Binding. It returns [] as the result of any model it finds although the record exists in the database.
 Consider this route:

Route::get('fundraisers/{fundraiser}', function (Fundraiser $fundraiser) {
    dd($fundraiser);
});

This is the result of putting the route in api.php:

#attributes: array:12 [
    "id" => 2
    "name" => "name"
    "national_id" => "111111111"
    "registration_number" => "1111111111"
    "registration_date" => "2011-11-11"
    "address" => "address"
    "postal_code" => "1111111"
    "legal_type" => null
    "info" => null
    "phone" => "09121111121"
    "created_at" => "2024-07-01 17:36:21"
    "updated_at" => "2024-07-01 17:36:21"
  ]

This is the result of putting the route in admin.php:

[]

The problem seemed to be about then: so I used web: in app.php.

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        api: __DIR__.'/../routes/api.php',
        apiPrefix: '',
        web: __DIR__.'/../routes/admin.php',
    )
    ->withMiddleware(function (Middleware $middleware) {
    })
    ->withExceptions(function (Exceptions $exceptions) {
        $exceptions->shouldRenderJsonWhen(fn() => true);
    })
    ->create();

It applied csrf token. So I used ->withoutMiddleware('web') it didn't help me with route model binding.

If I use any other fields like console, channel and etc, the route model binding issue persists. I need your help!


Solution

  • You need to add the SubstituteBindings middleware its a default middleware in web and api as you removed 'web' middleware so its removed from the request cycle

    if you want to get aware of csrf just change 'web' to 'api'

    check this documentation : https://laravel.com/docs/11.x/middleware#laravels-default-middleware-groups