Laravel validation exists where NOT

后端 未结 6 1830
温柔的废话
温柔的废话 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: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
    

提交回复
热议问题