Laravel:使用路由/模型绑定时在表单请求中访问模型实例 [英] Laravel: Access Model instance in Form Request when using Route/Model binding

查看:64
本文介绍了Laravel:使用路由/模型绑定时在表单请求中访问模型实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的项目中为我的一个模型设置了一些路线/模型绑定,并且效果很好.我可以在路由路径中使用绑定,并接受模型的实例作为控制器中相关方法的参数.

I have some route/model binding set up in my project for one of my models, and that works just fine. I'm able to use my binding in my route path and accept an instance of my model as a parameter to the relevant method in my controller.

现在我正在尝试对该模型进行一些工作,因此我在控制器中创建了一个接受Form Request的方法,以便可以进行一些验证.

Now I'm trying to do some work with this model, so I have created a method in my controller that accepts a Form Request so I can carry out some validation.

public function edit(EditBrandRequest $request, Brand $brand)
{
    // ...

可以对模型的每个不同实例进行不同的验证,因此,我需要能够使用模型的一个实例来构建一组自定义的验证规则.

Each different instance of my model can be validated differently, so I need to be able to use an instance of the model in order to build a custom set of validation rules.

是否可以获取从Form Request注入到控制器中的模型实例?

我尝试在Form Request的构造函数中提示模型实例

I have tried type-hinting the model instance in the Form Request's constructor

class EditBrandRequest extends Request
{
    public function __construct(Brand $brand)
    {
        dd($brand);
    }

我还尝试了在Form Request的 rules()方法中对模型实例进行类型提示.

I have also tried type-hinting the model instance in the Form Request's rules() method.

class EditBrandRequest extends Request
{
    // ...

    public function rules(Brand $brand)
    {
        dd($brand);

在这两种情况下,我都提供了一个空/新的模型实例,而不是我所期望的实例.

In both instances I am provided an empty/new instance of the model, rather than the instance I am expecting.

当然,我总是可以通过不打扰Form Requests来解决此问题,而只需在控制器中生成规则并手动进行验证-但如果可能的话,我宁愿使用 Laravel方法来解决.

Of course, I could always get around this by not bothering with Form Requests and just generate the rules in the controller and validate manually - but I would rather do it the Laravel way if it's possible.

谢谢

推荐答案

您可以简单地使用绑定键访问它,例如,如果您绑定 Brand 模型: $ router-> model('brand','\ App \ Brand'),您可以使用 $ this-> brand 获得模型的实例.这是验证规则示例:

You can simply access it using the binding key, so for example if you bind Brand model: $router->model('brand', '\App\Brand') you can get instance of your model with $this->brand. Here is validation rules example:

'slug' => 'required|unique:brand,slug,' . $this->brand->id,

编辑

有时您可能会有一个使用与绑定键相同名称的输入名称,例如,如果将 Address 模型与 address 绑定在一起,则您会有一个输入字段 address (地址)将使Laravel感到困惑.在这种情况下,您可以使用 route()方法.

Sometimes you might have an input name that uses the same name as the binding key, for example, if you bind Address model as address then you have an input field address it will make Laravel confuse. For this situation you can use route() method.

'address' => 'required|unique:addresses,address,' . $this->route('address')->id,

这篇关于Laravel:使用路由/模型绑定时在表单请求中访问模型实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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