首页 > 解决方案 > laravel blade syntax for loop how to call iteration index inside laravel helper functions

问题描述

I have the following for loop

@for($i = 0; $i < $contactAmount; $i++)
                <div class="form-group row">
                    <label for="firstname" class="col-md-4 col-form-label text-md-right">voornaam</label>

                    <div class="col-md-6">
                        <input id="firstname" type="text" class="form-control @error('firstname.0') is-invalid @enderror" name="firstname[]" value="{{ old('firstname.0') }}" autofocus>

                        @error('firstname.0')
                            <span class="invalid-feedback" role="alert">
                                <strong>{{ $message }}</strong>
                            </span>
                        @enderror
                    </div>
                </div>
@endfor

but if I replace the hard coded '0' with {{ $i }} my validation does not work anymore. So how do I call my integer and use it inside laravel helper functions?

 @for($i = 0; $i < $contactAmount; $i++)
                <div class="form-group row">
                    <label for="firstname" class="col-md-4 col-form-label text-md-right">voornaam</label>

                    <div class="col-md-6">
                        <input id="firstname" type="text" class="form-control @error('firstname.{{ $i }}') is-invalid @enderror" name="firstname[]" value="{{ old('firstname.'. $i) }}" autofocus>

                        @error('firstname.{{ $i }}')
                            <span class="invalid-feedback" role="alert">
                                <strong>{{ $message }}</strong>
                            </span>
                        @enderror
                    </div>
                </div>
@endfor

标签: laravelvalidationfor-looplaravel-bladehelper

解决方案


你为什么不使用一个@foreach?您可以按如下方式访问循环的索引:

@foreach($contactAmount as $amount)
   <div class="form-group row">
       {{ $loop->iteration }}
       ...
   </div>
@endforeach


推荐阅读