dpkrbe395930 2016-05-20 12:58
浏览 74
已采纳

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.

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.

Is there a way of getting the instance of the model, that is injected into the controller from the 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);
    }

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.

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.

Thanks

  • 写回答

1条回答 默认 最新

  • dqy13020940 2016-05-20 13:14
    关注

    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,
    

    EDIT

    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,
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 MATLAB动图的问题
  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名