frustratedprogrammer
frustratedprogrammer

Reputation: 25

Laravel: Displaying the error message of an input array specific index

I have an Input array and i want to output the error of each specific index so if my $input[0] and $input[1] meets an error they should be display while the other input lets say $input[2] didn't meet error then it shouldn't be display:

The mmad_bonus_type may confuse you because i'm using email for it. i'm just using the email validation rule for testing.

$length = $input['length'];

$rules = array();

for($i = 0, $c = $length; $i < $c; $i++){
  $rules['mmad_bonus_type'][$i] = 'email';
}

$validator = Validator::make($input, $rules, $message);

if($validator->fails()){
    return Response::json($validator->messages());
}
print_r($rules);

Heres the output of my print_r :

 [mmad_bonus_type] => Array
    (
        [0] => email
        [1] => email
        [2] => email
        [3] => email
    )

If i ran the code only single error outputted for the mmad_bonus_type input.

Here is the var_dump of my inputs:

 array(11) {
  ["length"]=>
  string(1) "2"
  ["mtype"]=>
  string(0) ""
  ["startfrom"]=>
  string(0) ""
  ["endfrom"]=>
  string(0) ""
  ["mmad_bonus_type"]=>
  array(1) {
    [0]=>
    string(0) ""
  }
  ["mmad_total_wins"]=>
  array(2) {
    [0]=>
    string(0) ""
    [1]=>
    string(0) ""
  }
  ["mmad_starting_date"]=>
  string(0) ""
  ["mmad_starting_time"]=>
  string(0) ""
  ["mmad_ending_date"]=>
  string(0) ""
  ["mmad_ending_time"]=>
  string(0) ""
  ["_token"]=>
  string(40) "ry0o35m0pP6xBF5N9YoXEUtMzGn50U36caJ4W37E"
}

Upvotes: 1

Views: 1892

Answers (1)

patricus
patricus

Reputation: 62278

The validator uses array_dot notation for the array keys. For example, if you had an input like <input type="text" name="user[name]" />, your validation rule would have the key 'user.name'.

The same format goes for numeric indexes, as well. So, if, for example, you had:

<input type="text" name="mmad_bonus_type[]" />
<input type="text" name="mmad_bonus_type[]" />
<input type="text" name="mmad_bonus_type[]" />

Then your validation rules would be:

$rules = array(
    'mmad_bonus_type.0' => 'email',
    'mmad_bonus_type.1' => 'email',
    'mmad_bonus_type.2' => 'email',
);

In your case, I'm assuming you have an array of mmad_bonus_type inputs with numeric indexes, so you're probably looking for something like:

for($i = 0, $c = $length; $i < $c; $i++){
    $rules['mmad_bonus_type.'.$i] = 'email';
}

Upvotes: 2

Related Questions