Laravel validation exists where NOT

2019-03-18 01:55发布

Based on the documentations. Exists can have 4 parameters:

exists:table,id,where,0

The question is, What if I wanted it to be where is not. Like where is not 0.

$validator = Validator::make(
    array(
        'groups' => $groups
    ),
    array(
        'groups' => 'required|exists:groups,jid,parent,!=,0'
    )
);

6条回答
SAY GOODBYE
2楼-- · 2019-03-18 02:04

You can use 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.

http://laravel.com/docs/4.2/validation#rule-unique

查看更多
Fickle 薄情
3楼-- · 2019-03-18 02:05

maybe you can try <> 0 ,that's the SQL for not equal

查看更多
The star\"
4楼-- · 2019-03-18 02:10

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;
});
查看更多
姐就是有狂的资本
5楼-- · 2019-03-18 02:16

With Laravel 5.2 or later you can prepend the values to be checked against with a !:

'groups' => 'required|exists:groups,jid,parent,!0'

The same login goes for unique, only you need the extra parameters:

'groups' => 'required|unique:groups,jid,NULL,id,parent,!0'
查看更多
姐就是有狂的资本
6楼-- · 2019-03-18 02:19

I know you're looking for 'not 0', but for reference sake, you can use NOT_NULL, as in:

'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)

查看更多
你好瞎i
7楼-- · 2019-03-18 02:23

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
查看更多
登录 后发表回答