Help us understand the problem. What is going on with this article?

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

やりたいこと

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

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした