Laravel 5 Validation唯一传递变量占位符 [英] Laravel 5 Validation unique pass variable placeholder

查看:212
本文介绍了Laravel 5 Validation唯一传递变量占位符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以将唯一的验证方法传递给带有变量的where子句?

Is it possible to pass the unique validation method extra where clauses with a variable?

这里有个例子:

在模型中,我有验证规则.

In my model I have my validation rules.

public static $rules = array(
    'amount'    => 'required|numeric',
    'user_id'   => 'required|exists:users,id',
    'cause_id'  => 'required|exists:causes,id',
    'circle_id' => 'required|unique:donations,circle_id,NULL,id,cause_id,:cause_id',
);

然后在我的控制器中运行:

And then in my controller I run:

$input = array(
    'amount'    => Input::get('amount'),
    'user_id'   => $this->currentUser->id,
    'cause_id'  => $cause->id,
    'circle_id' => Input::get('circle_id')
);

$validator = Validator::make($input, Donation::$rules);

如何在不将其串联的情况下在验证规则中获取cause_id?从rules数组可以看到,我尝试了PDO样式:placeholder,但是查询执行为: select count(*) as aggregate from donations where circle_id = '500' and cause_id = ':cause_id'

How can I get the cause_id in the validation rule without concatenating it? As you can see by the rules array, I have tried the PDO style :placeholder, but the query is executed as: select count(*) as aggregate from donations where circle_id = '500' and cause_id = ':cause_id'

推荐答案

我的建议是将规则包装在函数中

My suggestion in your case would be to wrap your rules in a function:

public static function rules($causeId)
{
    return array(
        'amount'    => 'required|numeric',
        'user_id'   => 'required|exists:users,id',
        'cause_id'  => 'required|exists:causes,id',
        'circle_id' => 'required|unique:donations,circle_id,NULL,id,cause_id,' . $causeId,
    );
}

然后调用您的函数,并传递您的值:

And then call your function, passing in your value:

$validator = Validator::make($input, Donation::rules($yourCauseId));

我过去曾经遇到过这样的问题,我也想使用其他字段中的值,规则中也要使用其他字段.这往往是解决它的最简单方法.

I've had problems like this in the past, I've also wanted to use the values from other fields, in the rule for another field too. This tends to be the easiest way to get around it.

这篇关于Laravel 5 Validation唯一传递变量占位符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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