php Laravel 验证存在于不存在的地方
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20785473/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Laravel validation exists where NOT
提问by majidarif
Based on the documentations. Exists can have 4 parameters:
基于文档。Exists 可以有 4 个参数:
exists:table,id,where,0
The question is, What if I wanted it to be where is not. Like where is not 0.
问题是,如果我想要它在什么地方不是。就像 where 不是 0。
$validator = Validator::make(
array(
'groups' => $groups
),
array(
'groups' => 'required|exists:groups,jid,parent,!=,0'
)
);
采纳答案by Vladislav Rastrusny
You can use something like this:
你可以使用这样的东西:
Validator::extend('not_exists', function($attribute, $value, $parameters)
{
return DB::table($parameters[0])
->where($parameters[1], '=', $value)
->andWhere($parameters[2], '<>', $value)
->count()<1;
});
回答by Cas Bloem
You can use unique
您可以使用 unique
Example
例子
'email' => 'unique:users,email_address,NULL,id,account_id,1'
In the rule above, only rows with an account_id of 1 would be included in the unique check.
在上面的规则中,只有 account_id 为 1 的行才会包含在唯一检查中。
回答by Tomas Buteler
With Laravel 5.2 or later you can prepend the values to be checked against with a !:
使用 Laravel 5.2 或更高版本,您可以在要检查的值之前添加一个!:
'groups' => 'required|exists:groups,jid,parent,!0'
The same login goes for unique, only you need the extra parameters:
同样的登录也适用于unique,只需要额外的参数:
'groups' => 'required|unique:groups,jid,NULL,id,parent,!0'
回答by Captain Hypertext
I know you're looking for 'not 0', but for reference sake, you can use NOT_NULL, as in:
我知道您正在寻找 'not 0',但为了参考起见,您可以使用NOT_NULL,如下所示:
'groups' => 'required|exists:groups,jid,parent,NOT_NULL'
It's not listed in the docs right now, but here is the discussion about it (see very last post)
它现在没有在文档中列出,但这里是关于它的讨论(见最后一篇文章)
回答by Buraco
A custom validator is here
自定义验证器在这里
Validator::extend('not_exists', function($attribute, $value, $parameters, $validator)
{
$table = array_shift($parameters);
$db = \DB::table($table);
foreach ($parameters as $parameter)
{
$check = explode(';', $parameter);
$col = array_shift($check);
$value = array_get($check, 0, array_get($validator->getData(), $col, false));
$db->where($col, $value);
}
return $db->count() < 1;
});
Example usage:
用法示例:
not_exists:model_has_roles,role_id,model_type;App\User,model_id
You can pass default value like this:
您可以像这样传递默认值:
model_type;App\User
回答by Giaken
maybe you can try <> 0,that's the SQLfor not equal
也许你可以试试<> 0,那是不相等的SQL

