Search code examples
phplaravelroutesmodel-bindingnested-routes

Nested Route Implicit Binding Laravel Return 404


So, this is my code.

web.php

Route::get(
    "/research/{research}/sub-research/{sub-research}", 
    function (Research $research, SubResearch $subResearch) {
        dd($research , $subResearch);
    }
)
    ->name("sub-research.show");

Research model

public function subResearch()
{
    return $this->hasMany(SubResearch::class, "research_id", "id");
}

SubResearch.php model

public function research()
{
    return $this->belongsTo(Research::class);
}

My problem is, when I access the route, I got 404 page. Laravel's documentation says:

When using a custom keyed implicit binding as a nested route parameter, Laravel will automatically scope the query to retrieve the nested model by its parent using conventions to guess the relationship name on the parent. In this case, it will be assumed that the User model has a relationship named posts (the plural form of the route parameter name) which can be used to retrieve the Post model.

How can I know what is laravel guessing as my relationship method name? Is it the same or not? Or maybe is this some other problem? What do you think?


Solution

  • The route segment name have to be the same to the route function variable name.Use {subResearch} instead of {sub-research}

    Route::get(
        "/research/{research}/sub-research/{subResearch}", 
        function (Research $research, SubResearch $subResearch) {
            dd($research , $subResearch);
        }
    )
        ->name("sub-research.show");