Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

For loop in Laravel validation

Tags:

php

laravel

How can I make something like this:

for($x=0; $x<=14; $x++) {
    $this->validate($request, [
        'name' => 'required',
        'radio_'.$x => 'required',
    ]);
}

But I need loop only over radio_ not name. Like this, but it's wrong:

$this->validate($request, [
    'name' => 'required',
    for($x=0; $x<=14; $x++) {
        'radio_'.$x => 'required',
    }
]);

My blade file, if it will help:

@for($x = 0; $x <= 14; $x++)
    <div class="form-group">
        <label for="radio">
            <li>@lang('leadersCompetence.questions.'.$x)</li>
        </label><br>
        @for($i = 0; $i <= 4; $i++)
            <label class="radio-inline">
                <input type="radio" name="radio_{{$x}}" @if(old('radio_'.$x) == $option[$i]) checked
                       @endif value="{{$option[$i]}}" required>
                {{$option[$i]}}
            </label>
        @endfor
    </div>
@endfor
like image 840
Arturs Avatar asked Sep 07 '25 20:09

Arturs


2 Answers

You can do it like this by creating validation array::

$validate_array = ['name' => 'required'];
 for($x=0; $x<=14; $x++) {
     $validate_array['radio_'. $x] = 'required';
 }
$this->validate($request, $validate_array );
like image 200
Rana Ghosh Avatar answered Sep 09 '25 14:09

Rana Ghosh


You can put your values into radios array and then use

'radios.*' => 'required'

in your controller.

like image 29
user3529607 Avatar answered Sep 09 '25 13:09

user3529607