【问题标题】:Laravel unique validation for multiple values from tags inputLaravel 对来自标签输入的多个值进行唯一验证
【发布时间】:2015-06-18 15:46:15
【问题描述】:

我需要对标签输入使用 laravel 唯一验证,但我面临多个值的问题,唯一规则在插入一个值时效果很好,但是当添加多个值时它不起作用。

这是我的控制器代码

 public function createteacher()
 {
     $rules = array (
         'teacher-name'  => 'required|unique:teacher,name',
     );

     $msgs =array(
         'teacher-name.required' => 'please insert teacher name',  
         'unique' => 'teacher name already exist',
     );

     $validator = Validator::make(Input::all(),$rules,$msgs);

     if ($validator->fails())
     {
         return  Response::json(['success'=>false,'error'=>$validator->errors()->toArray() ]);
     }
     else
     {
         $c = count(explode(',', Input::get('teacher-name')));

         $teachers_ids = explode(',', Input::get('teacher-name'));

         //if Validated
         for ($i = 0 ; $i < $c ; $i++)
         {
             $new_teacher = Teacher::firstOrCreate(array('name'=>$teachers_ids[$i]));  
         }

         return Response::json(['success'=>true]); 
     }
 }

这是我的视图代码

<div class="col-md-6">
 <div class="box box-redorange">
  <div class="box-header">
   <h3 class="box-title" style="float:right"> Adding Teachers </h3>
  <i class="fa fa-spinner fa-spin fa-lg" style="display:none float:left;" id="teacher-adding-load"></i> &nbsp;
   </div>
  <div class="box-body">                                    

     {{Form::open(array('url'=>'management/createteacher','id'=>'teacher-form'))}}
   <div class="form-group">
    <label for="teacher-name[]">Teacher Name </label>
    <select multiple data-role="tagsinput" name="teacher-name[]"   id="teacher-name" class="form-control" autofocus="true">
           <option value="" ></option>
    </select>
      </div>                     
      </div> <!-- end box body-->
      <div class="box-footer">
      {{Form::submit('Add',array('style'=>'color:#fff;font-weight:bold; ','class' => 'btn btn-redorange btn-block btn-sm')) }}
       {{Form::close()}}
       </div> <!--end box footer -->
       </div> <!-- end box -->
       <div class="form-group help-block teahcer-form-msgs" style="display:none;">
             <small></small>
       </div> 
      </div> <!-- end col-m-6 -->

终于有了我的ajax代码

 $(document).ready(function(){

 var msgs = $('.teahcer-form-msgs');

 $('#teacher-form').submit(function(e){
  e.preventDefault();
 var $teacher_loading = $('#teacher-adding-load').show();

   // form data
    var formData = new FormData ();

     formData.append('teacher-name' , $('#teacher-name').val());

 $.ajax({
 url:'/elaqsacenter/public/management/createteacher',
 method:'post',
 processData:false,
 contentType:false,
 cache:false,
 dataType: 'json',
 data:formData,
 complete:  function(){
      $teacher_loading.hide();
  },
   global: false,
   success:function(data){

   msgs.hide().find('small').empty();

   if (!data.success) {

    $.each(data.error,function(index,error){

        msgs.find('small').append('<p class="text-danger">'+'<span     

       class="glyphicon glyphicon-exclamation-sign" aria-hidden="true">

       </span>'+' '+error+'</p>');

      // disable submit button when throw Validation messages 
     $('input[type=submit]').prop("disabled", true);
       setTimeout(function() {
       $('input[type=submit]').prop("disabled", false);
      }, 4000);
  });
    msgs.slideDown();
    msgs.delay(3000).slideUp();

  }else{
 msgs.find('small').append('<p class="text-success">data Inserted</p>');
      msgs.slideDown();
      msgs.delay(3000).slideUp();
      setTimeout(function(){location.reload();},2000);  
   }

 },
  global: false,
  error:function(){},

   });

  });

});

我的主要问题是如何使用通过标签输入插入多个值的唯一规则

【问题讨论】:

    标签: php ajax laravel laravel-4 laravel-validation


    【解决方案1】:

    我也遇到了同样的问题。问题是您正在提交一个数组 [] teacher-name[]。鉴于此,假设在提交后您可以通过键入以下内容输出您拥有的整个数组:

    $data=Input::all();
                echo '<p style="color: blue;">The array data submitted are :<br><strong>'.print_r(Input::all(),true).'</strong></p>';
                die();
    

    你会注意到你实际上是在一个数组中得到一个数组。所以验证需要一个值数组,而不是数组数组。

    要解决这个问题,您需要使用 foreach 函数。仅出于测试目的,假设教师姓名的长度不应超过 5 个字符:

        $data=Input::all();
                    echo '<p style="color: blue;">The array data submitted are :<br><strong>'.print_r(Input::all(),true).'</strong></p>';
    foreach ($data['teacher-name'] as $key => $value) {
    $validacion=Validator::make(
                            array(
                                $key    =>  $value
                                ),
                            array(
                                $key    =>  'max:5'
                                ),
                            array(
                                'max'   => 'In Spanish i\'d say this field can\'t be greater than :max chars...'
                                )
                            );
                        if($validacion->fails()){
                            echo '<p style="color: red;">Validation has failed for <b>'.$value.'</b></p>';
                        }
    }
                die();
    

    所以,解决方案是在为Input::all()提交数组时必须使用foreach函数。

    【讨论】:

    • 感谢 pathros 的回答,请看我的回答也许有用。再次感谢
    • @JustUser 是的,它很有用!谢谢 :) ☺
    【解决方案2】:

    我发现更简单的方法可以遍历 tagsInput 值来验证它,如下所示

       $c = count(Input::get('teacher-name') );
    
        //In view the name must be  name="teacher-name[]"
       $teacher_name =Input::get('teacher-name');
    
       /* To loop over multiple values that insert from tags input.
          you can add all laravel validation with this way .
          and custom :attribute by setAttributeNames() method */      
        for ($i = 0; $i < $c ; $i++){
    
       $rules[$i] = 'required|between:3,15';
    
       $customAttributes[$i] =  $i + 1  ;
    }
    
        $msgs =  array('required' => '.Teacher Name Is Required' ,
                       'between' => '.Teacher Num  (:attribute) must be between 3 : 15 chars' ) ; 
    
        $validateTeacher = Validator::make($teacher-name,$rules,$msgs);
        $validateTeacher->setAttributeNames($customAttributes); 
    
          if ($validateDivision->fails() OR $validateGrade->fails()) 
        {
           // return Ajax Validation Messages OR laravel Validation Messages 
        }
    

    通过上面的方式,你可以一个一个循环遍历tagsInput的值,享受吧:)

    【讨论】:

      猜你喜欢
      • 2019-05-08
      • 1970-01-01
      • 2018-10-25
      • 1970-01-01
      • 2022-01-12
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2022-08-15
      相关资源
      最近更新 更多