4
7

More than 3 years have passed since last update.

Laravel で バリデーションエラー時にJSで動的に増やしたinputの値を保持する

Posted at

やりたいこと

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

4
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
7