【发布时间】:2016-11-22 16:32:13
【问题描述】:
对于自定义验证规则是否需要返回 true 或 false 来触发,我有点困惑。
我正在验证一个电子邮件地址,以使其确实通过关系属于另一个模型。
Validator::extend('email_exists', function($attribute, $value, $parameter){
$user = User::where('email', '=', $value)->with('clients')->first();
//Does the user exits, and are they already a member of this client?
//We know this by looking at the client id, and comparing them the current ID.
if($user != NULL) {
if(in_array(Input::get('client_id'), $user->clients->lists('id'))) {
return false;
} else {
return true;
}
} else {
return true;
}
});
我在上面尝试的是,查找输入的电子邮件是否存在用户,如果确实存在,则检查该电子邮件是否与任何客户相关,以及这些客户 id 是否与POST,如果电子邮件存在并且与 POST 中的客户端 ID 相关,我想返回一个错误,否则我很乐意处理 POST。
目前,我认为我允许任何事情通过。我是否正确使用了自定义规则,如果我想抛出错误应该返回什么?
【问题讨论】:
-
看起来是正确的,你有没有把这段代码放在服务提供者里面,如果是的话,你记得把服务提供者添加到
config/app.php的提供者数组吗? -
它现在直接在我的控制器中。
-
只是确保表单提交到控制器的部分,而不是负责构建表单的部分?还可以尝试在设置
$uservar 之前在其中添加dd('test');以查看它是否曾经进入该部分。
标签: php validation laravel laravel-4