Search code examples
phplaravellaravel-4laravel-validation

laravel 4 validation issue


I have this code in Controller store function to validate values of input tags

 $c = count(Input::get('division-name') );

   $divs_ids =  Input::get('division-name');

   $grade_name =Input::get('grade-name');

   // this loop for multiple values that insert from tags input.
    for ($i = 0; $i < $c ; $i++){

   $rules[$i] = 'required|min:5';

   $msgs =  array('required' => 'Division name is required ','min' => 'the :attribute must be at least 5 characters. ') ; 


         }

    $validateDivision = Validator::make($divs_ids,$rules,$msgs);

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


      if ($validateDivision->fails() OR $validateGrade->fails()) {

          $validationMessages = array_merge_recursive($validateGrade->messages()->toArray(),
                                                      $validateDivision->messages()->toArray());            


             return    Redirect::back()->withErrors($validationMessages)->withInput();


    }else{
                  ..............

The issue, that the validation message of min validation

show >>> The 0 must be at least 5 characters.

how i can toggle (0) by the input name, or toggle (0) to start of (1)


Solution

  • The values that will be replacing the :attribute tag in your error message will be the keys of your $divs_ids array.

    But laravel allows you to use custom attributes name.

    First you need to create an array containing your attributes name. You can do that in the for loop you already have :

    for ($i = 0; $i < $c ; $i++){
        $rules[$i] = 'required|min:5';
        $customAttributes[$i] = 'Division name n°' . $i + 1; //For exemple
    }
    

    Now you can use that array like this:

    $validateDivision = Validator::make($divs_ids,$rules,$msgs);
    $validateDivision->setAttributeNames($customAttributes); 
    

    This way, your error message should display the custom attributes names.