【问题标题】:Laravel not loading model into routeLaravel 没有将模型加载到路由中
【发布时间】:2017-06-03 02:34:03
【问题描述】:

我目前正在开发一个 PHP Laravel 应用程序,到目前为止一切进展顺利。但是,我最新的名为FreightRequest 的资源导致了我无法弄清楚的极其奇怪的行为。

我的路由文件有以下内容:

Route::resource('freightrequests', 'FreightRequestController');

当我访问 http://localhost/freightrequests/1 时,laravel 没有正确地将模型绑定到我的 FreightRequestController@show 方法。

我的方法是这样的:

public function show(FreightRequest $freightRequest)
{
    dd($freightRequest);

    return view('freightrequests.show', compact('freightRequest'));
}

以上结果如下转储:

FreightRequest {#429 ▼
  #connection: null
  #table: null
  #primaryKey: "id"
  #keyType: "int"
  +incrementing: true
  #with: []
  #withCount: []
  #perPage: 15
  +exists: false
  +wasRecentlyCreated: false
  #attributes: []
  #original: []
  #casts: []
  #dates: []
  #dateFormat: null
  #appends: []
  #events: []
  #observables: []
  #relations: []
  #touches: []
  +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
  #guarded: array:1 [▶]
}

事实上,如果我转到一个不存在的 ID http://localhost/freightrequests/12343243,Laravel 不会抛出 NotFoundHttpException。如果我访问http://localhost/users/12343243,我会得到NotFoundHttpException。除了这个资源之外,我所有的其他资源都可以正常工作。

我什至尝试放弃 Route::resource 并将其替换为:

Route::get('freightrequests/{freightrequest}', 'FreightRequestController@show')->name('freightrequests.index');

我尝试重命名模型、控制器、路由和所有内容,以防出现冲突导致 Laravel 无法检索模型。它似乎正在注入正确的类实例,但实际上并未尝试从服务器获取它。我试过清除缓存。我绝对无法弄清楚为什么这个特定模型无法正常工作,而我的其他 6 个左右的资源却没有问题。

有什么想法吗?

【问题讨论】:

  • 您的FreightRequest似乎有问题
  • freight_requests 表中是否有id 列?

标签: php laravel laravel-5


【解决方案1】:

我在发布问题后不久就发现了问题:

public function show(FreightRequest $freightRequest)
{
   dd($freightRequest);

   return view('freightrequests.show', compact('freightRequest'));
}

应该是:

public function show(FreightRequest $freightrequest)
{
    dd($freightrequest);

    return view('freightrequests.show', compact('freightrequest'));
}

在尝试绑定参数时区分大小写很重要,我花了很长时间才意识到 R 是大写 :)

【讨论】:

  • 是的,我也遇到了同样的问题——如果你使用 artisan 命令创建资源控制器,laravel 甚至会生成“错误”大写的变量 $freightRequest
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-10-10
  • 1970-01-01
  • 2020-12-16
  • 2016-08-16
  • 2014-09-16
  • 2018-12-19
  • 2020-11-16
相关资源
最近更新 更多