Laravel validation exists where NOT

后端 未结 6 1831
温柔的废话
温柔的废话 2021-02-04 04:58

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. Lik

相关标签:
6条回答
  • 2021-02-04 05:23

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

    0 讨论(0)
  • 2021-02-04 05:28

    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;
    });
    
    0 讨论(0)
  • 2021-02-04 05:37

    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)

    0 讨论(0)
  • 2021-02-04 05:40

    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

    0 讨论(0)
  • 2021-02-04 05:42

    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'
    
    0 讨论(0)
  • 2021-02-04 05:48

    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
    
    0 讨论(0)
提交回复
热议问题