Laravel 修改路由参数为 name 列而不是 id

3x0*_*71c 2 php variables http-status-code-404 laravel laravel-5

在我的web.php文件中,我指定了以下路线:

Route::get('/{project}', 'ProjectsController@index');
Run Code Online (Sandbox Code Playgroud)

在我的 ProjectsController 中,我定义公共函数index如下:

use App\Project;
// ... Here is the class declaration etc.
public function index(Project $project) {
  dd($project->name);
}
Run Code Online (Sandbox Code Playgroud)

目前,我的项目表中有一个条目,我可以通过我的雄辩模型毫无问题地调用它。这是我的条目:

Name: sampleproject
Description: This is a test.
ID: 1
// And the timestamps...
Run Code Online (Sandbox Code Playgroud)

当调用 时/sampleproject,它会返回 404 错误页面。
[...]

更新:当调用/1,即项目 id 时,一切都按预期进行。如何修改我的代码,以便我可以通过项目名称而不是 id 调用我的控制器?

小智 6

在你的模型中:

public function getRouteKeyName()
{
    return 'yourcolumn';
}
Run Code Online (Sandbox Code Playgroud)