やりたいこと
jsで下記のようなinputをボタンを押したら追加していくというような可変な入力欄のとき
バリデーションエラーが起きたら、行が増えた状態で、それぞれに値が保持されていてほしい
test.blade.php
<div>
<input type="text" name="hoge[]">
</div>
やりかた
Laravel 6.6で確認しています
バリデーションエラーが起こった時 old('hoge.0')
とやれば、一番初めの入力値がとれます。
つまり、indexを指定してあげればその値が、指定しなければ配列そのものが取れます。
old('hoge.0');
old('hoge.1');
// hoge
// hoge2
old('hoge');
// [0 => hoge, 1 => hoge2]
なので、blade側でエラー時にループしてあげれば増えた状態で
入力値を保持できます
test.blade.php
@empty(old('hoge'))
<div>
<input type="text" name="hoge[]">
</div>
@else
@foreach(old('hoge') as $value)
<div>
<input type="text" name="hoge[]" value="{{$value}}">
</div>
@endforeach
// ↑↓ どっちでも($loop->indexでも)
@foreach(old('hoge') as $key => $value)
<div>
<input type="text" name="hoge[]" value="{{old('hoge.{$key}')}}">
</div>
@endforeach
@endempty