manoos
manoos

Reputation: 1735

How to validate inputs with variables as input name laravel?

I am trying to validate the inputs from view file, that is given below

@foreach($persons as $person)              
  <div class="form-group{{ ($errors->has($person->id)) ? 'has error' : '' }}">
    <label for="{{$person->id}}" class="col-sm-4 control-label">{{$student->sname}}:</label>
    <div class="col-sm-8">
      <input id="{{$person->id}}" name="{{$person->id}}" type="text" class="form-control" value="Enter Age">
      @if($errors->has($person->id))
        {{ $errors->first($person->id)}}
      @endif
    </div>
  </div>
@endforeach

I want to validate $person->id field is entered or not? How will I do?

If this names are constant, I know how to validate by using

$validate = Validator::make(Input::all(), array(
    'sname' => 'required'          
)); 

But here name of inputs are variables. then how will I validate these inputs??

Upvotes: 2

Views: 993

Answers (1)

user1669496
user1669496

Reputation: 33058

This probably isn't a path you want to be going down with variable input names. When adding inputs in a loop, it's usually a much better idea to have your names as arrays.

In the event that can't be done, what you need to do is possible. The names of these values will be coming over as the keys of Input::all() so what you can do is take those and query your database to determine which inputs are actually user id's. Then you should be able to take that list of id's and set their keys as the rule you want, in this case required.

I just came up with this and it seems to be working okay for me. You might have to change the User model to what is appropriate for you (Person model maybe?).

$rules = User::select('id', DB::raw('\'required\' as rule'))->whereIn('id', array_keys(Input::all()))->lists('rule', 'id');

This will break though if there is ever another input name that also happens to be a user's id. If id's are only ever numbers and you don't allow user names to be only numbers, then it might work out.

Upvotes: 1

Related Questions