以模型为参数的资源控制器方法不起作用 [英] Resource Controller methods with model as parameter not working

查看:48
本文介绍了以模型为参数的资源控制器方法不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就像基本的Laracasts.com教程(从零开始的Laracast 5.7)一样,我试图使用以下方法 public function show(prototypes $ prototypes)参数来构建视图.但是我的视图创建正确,但是 $ prototypes 为空.

As in the basic Laracasts.com tutorial (Laracast 5.7 from scratch) I'm trying to use the following methods public function show(prototypes $prototypes) parameter to construct a view. However my view is created correctly but $prototypes is null.

路由运行良好(/prototypes/1/edit),我确保存在一个 ID 为 1 的 prototype 对象.我找到了一些较旧的解决方案,该解决方案声明使用诸如(integer $ id)之类的参数,但这会导致更多代码.它应该像这样工作:

The route works well(/prototypes/1/edit) and I ensured that a prototype object with the id 1 exists. I found some older solution which stated to use something like (integer $id) as parameter but this leads to some more code. It should work like this:

控制器:

public function edit(prototypes $prototypes)
{
    //
    return view('prototypes.edit', compact('prototypes'));
}

根据从头开始播放,这应该可以.

您知道我该如何解决吗?

Do you know how I could fix this?

prototypes.edit 方法知道如何使用正确的参数的背后机制是什么?

What mechanism is behind this that the prototypes.edit method knows how to use the correct parameter?

推荐答案

对于隐含使注入的变量名称有效的模型绑定应该与 route参数名称相匹配,在您的情况下,我认为您的参数名称可以为 {prototype},您可以通过在控制台中发出命令 php artisan route:list 来进行验证.

For the Implicit Model Binding to works the injected variable name should match the route parameter name, in your case I think that your parameter name could be {prototype}, you can verify it by issuing the command php artisan route:list in the console.

如果是这样,则必须在控制器函数中将变量名称更改为 $ prototype (请注意单数形式)以匹配参数名称 {prototype} ,像这样:

If that is true you have to change the variable name to $prototype (please note the singular) in your controller function to match the parameter name {prototype}, like this:

public function edit(prototypes $prototype)
{
   return view('prototypes.edit', compact('prototype'));
}

更新:顺便说一句,关于Model名称的laravel约定是单数驼峰式,在您的情况下,您的Model应该命名为 Prototype 而不是 Prototypes ,即:

Update: BTW the laravel convention on Model's name is singular camel case, in your case your Model should be named Prototype not prototypes, i.e.:

public function edit(Prototype $prototype)
{
   return view('prototypes.edit', compact('prototype'));
}

这篇关于以模型为参数的资源控制器方法不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆