LoginSignup
24
17

More than 5 years have passed since last update.

Laravelで多次元配列のバリデーション

Last updated at Posted at 2018-03-16

書き方

inputタグのname属性がcomment[数字][]の場合です。

$validator = Validator::make($request->all(), [
    'comment' => 'required|array',
    'comment.*' => 'required|array',
    'comment.*.*' => 'nullable|string|max:255',
]);

if ($validator->fails())
{
    return redirect()->back()->withErrors($validator->errors())->withInput();
}

画面例

foreachで展開できなかったので仕方なくforで展開します。

@if (old('comment'))
    @for ($index = 0; $index < count(old('comment')); $index++)
        @for ($index2 = 0; $index2 < count(old('comment.'.$index)); $index2++)
            @if ($errors->has('comment.'.$index.'.'.$index2))
                <div style="color:red;">{{ $errors->first('comment.'.$index.'.'.$index2) }}</div>
            @endif
        <input type="text" name="comment[{{ $index }}][]" value="{{ old('comment.'.$index.'.'.$index2) }}" maxlength="255">
        @endfor
    @endfor
@endif
24
17
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
24
17