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

Laravel modify route parameter to name column instead of id

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

Route::get('/{project}', 'ProjectsController@index');

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

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

目前,我的项目 table 中有一个条目,我可以毫无问题地调用我的 eloquent 模型。这是我的条目:

Name: sampleproject
Description: This is a test.
ID: 1
// And the timestamps...

当调用 /sampleproject 时,它 returns 一个 404 错误页面。
[...]

更新: 调用项目 ID /1 时,一切正常。如何修改我的代码,以便我可以通过项目名称而不是 ID 调用我的控制器?

在您的模型中:

public function getRouteKeyName()
{
    return 'yourcolumn';
}