【问题标题】:Laravel modify route parameter to name column instead of idLaravel 将路由参数修改为 name 列而不是 id
【发布时间】:2019-07-31 14:06:56
【问题描述】:

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

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

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

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

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

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

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

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

【问题讨论】:

标签: php laravel variables laravel-5 http-status-code-404


【解决方案1】:

在您的模型中:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-02-10
    • 2021-04-03
    • 2013-03-14
    • 2021-08-31
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多