Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

omontes's avatar

How Validate multiple fields

How Validate multiple fields, two requerid, use Laravel 4.0

{{ Form::text("percent[{$key}]",Input::old("percent[{$key}]") }}
{{ Form::textarea("description[{$key}]" }}
0 likes
32 replies
bestmomo's avatar

If you have percent[0] you write :

percent.0' => 'required...',

in validation.

omontes's avatar

the form contains 46 inputs (percent) and 46 input (description)

percents = Input::get('percent');
descriptions = Input::get('description');


foreach ($percents  as $key => $percent) {
$fields['percent'.$key] = $percent;
$rules['percent'.$key] = 'required|numeric|between:0,100';
}
$validator = Validator::make($fields, $rules);

if ($validator->fails())
{
    return Redirect::back()->withErrors($validator)->withInput();
}

and descriptions validations????

bestmomo's avatar

Try :

'percent' => 'required|each:numeric|each:between:0,100'
omontes's avatar
foreach ($percents as $key => $percent) {
//$fields['percent'.$key] = $percent;
$fields = array('percent'.$key => $percent);    
$rules['percent'.$key] = 'required|each:numeric|each:between:0,100';
}
$validator = Validator::make($fields, $rules);

if ($validator->fails())
{
    return Redirect::back()->withErrors($validator)->withInput();
}

as valid the descriptions - descriptions = Input::get('description');?

bestmomo's avatar

I say to test the 'each' in rule to avoid the great foreach.

1 like
omontes's avatar

think it is impossible to eliminate forech

$fields $rules

bestmomo's avatar

The each can work like this :

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

$v->each('percent', ['required|numeric|between:0,100']);

if ($v->fails()) {
  ...
}
omontes's avatar
$percents = Input::get('percent');

$v->each('percents', ['required|numeric|between:0,100']);

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

if ($v->fails())
{
    return Redirect::back()->withErrors($validator)->withInput();
}

not working, error "Call to a member function each() on a non-object"

thepsion5's avatar

Well you have to create the validator instance before you can start calling methods on it. Basic PHP. ;)

omontes's avatar

Excuse me, really do not know how to do, could you tell me how?

omontes's avatar

Worked as follows, but would like to improve the code

//Form
{{ Form::text("percents[{$key}]") }}
{{ Form::textarea("descriptions[{$key}]") }}


//Controller
$percents = Input::get('percents');
$descriptions = Input::get('descriptions');

foreach ($porcentajes as $key => $porcentaje)
{
$fields['percents'.$key] = $porcentaje;
$fields['descriptions'.$key] = $descriptions[$key] ;
$rules['percents'.$key] = 'required|numeric|between:0,100';
$rules['descriptions'.$key] = 'required';
}

$validator = Validator::make($fields, $rules);

if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}

//View
{{ str_replace('percents'.$key, 'Percent', $errors->first('percents'.$key, '<p class="text-danger">:message</p>')) }}

{{ str_replace('descriptions'.$key, 'Description', $errors->first('descriptions'.$key, '<p class="text-danger">:message</p>')) }}
bestmomo's avatar

Try it in controller :

//Controller
$validator = Validator::make(Input::all(), []);

$validator->each('percents', ['required|numeric|between:0,100']);
$validator->each('descriptions', ['required']);

if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}
omontes's avatar

I did what you indicated me,not work

$percents = Input::get('percents');
$descriptions =  Input::get('descriptions');

$validator = Validator::make(Input::all(), []);

$validator->each('percents', ['required|numeric|between:0,100']);
$validator->each('descriptions', ['required']);

if ($validator->fails())
{
return Redirect::back()->withErrors($validator)->withInput();
}

I have this error BadMethodCallException Method [each] does not exist.

bestmomo's avatar

I've just checked with this code in L4 and it works :

$validator = Validator::make(Input::all(), []);
$validator->each('mytext', ['required']);
if ($validator->fails())
{
    dd('fails');
}
dd('ok');

The method "each" exists in validator :

/**
 * Define a set of rules that apply to each element in an array attribute.
 *
 * @param  string  $attribute
 * @param  string|array  $rules
 * @return void
 *
 * @throws \InvalidArgumentException
 */
public function each($attribute, $rules)
{
    $data = array_get($this->data, $attribute);

    if ( ! is_array($data))
    {
        if ($this->hasRule($attribute, 'Array')) return;

        throw new \InvalidArgumentException('Attribute for each() must be an array.');
    }

    foreach ($data as $dataKey => $dataValue)
    {
        foreach ($rules as $ruleValue)
        {
            $this->mergeRules("$attribute.$dataKey", $ruleValue);
        }
    }
}
omontes's avatar

That does not happen, tell you what I do:

//Form
@foreach($estaciones as $key => $estacion)
{ Form::text("porcentaje[{$key}]",Input::old("porcentaje[{$key}]"),array('class' => $key , 'readonly' => 'readonly','style' => "border:0; color:#f6931f; font-weight:bold;")) }}
{{ Form::textarea("observaciones[{$key}]") }}
 @endforeach
{{ Form::submit('Guardar', array('class' => 'btn btn-info')) }}
{{ Form::close() }}

//Controller
$porcentajes = Input::get('porcentaje');
$observaciones =  Input::get('observaciones');

$validator = Validator::make(Input::all(), []);
$validator->each('porcentajes', ['required']);
if ($validator->fails())
{
    dd('fails');
}
dd('ok');

I have this error

Method [each] does not exist.

bestmomo's avatar

Better like it :

//Controller
$validator = Validator::make(Input::all(), []);
$validator->each('porcentaje', ['required']);
if ($validator->fails())
{
    dd('fails');
}
dd('ok');

Your input array is 'porcentaje" and not "porcentages".

And you dont need these lines :

$porcentajes = Input::get('porcentaje');
$observaciones =  Input::get('observaciones');
charlesBR's avatar

@omontes, apparently you are missing a dot when concatenating the fields and rules names:

// you have:
$fields['percent' . $key] = $percent;
$rules['percent' . $key] = 'required|numeric|between:0,100';

// you should have a dot INSIDE the string as well:
$fields['percent.' . $key] = $percent;
$rules['percent.' . $key] = 'required|numeric|between:0,100';
omontes's avatar

@bestmomo, continuous error

$validator = Validator::make(Input::all(), []);
$validator->each('porcentaje', ['required']);
if ($validator->fails())
{
    dd('fails');
}
dd('ok');

it works for you ?

I do wrong?

Method [each] does not exist.

bestmomo's avatar

@omontes I dont understand because it's ok for me. Have you an updated version of Laravel ? Check the "each" method in vendor/laravel/framework/src/Illuminate/Validation/Validator.php.

omontes's avatar

version to work: Laravel 4

"require": {
        "laravel/framework": "4.0.*"

in vendor/laravel/framework/src/Illuminate/Validation/Validator.php not "each"

omontes's avatar

Laravel can be updated only by editing the composer.json ?

change "laravel/framework": "4.0.", by "laravel/framework": "4.2.",

charlesBR's avatar

Don't forget to run composer update after. I'm not sure if there might be any incompatibility issues upgrading from one version to another, though.

omontes's avatar

Update laravel 4.2 and validation works but I have problems printing the error next to the input

{{ str_replace('porcentaje'.$key, 'Porcentaje', $errors->first('porcentaje'.$key, '<p class="text-danger">:message</p>')) }}
omontes's avatar

solve it

{{ str_replace('porcentaje.'.$key, 'Porcentaje', $errors->first('porcentaje.'.$key, '<p class="text-danger">:message</p>')) }}
Next

Please or to participate in this conversation.