LoginSignup
0
1

More than 3 years have passed since last update.

【Laravel】foreachで配列回して送信したcheckboxのoldを取得する

Last updated at Posted at 2020-02-14

環境

  • PHP 7.4.1
  • Composer 1.9.3
  • Laravel Framework 6.14.0
  • laravelcollective/html v6.0.3

結論

laravelcollective/html入れてFormファサード使ったら、勝手に直前の入力値をcheckedにしてくれました。
便利すぎて震えた。oldなんて書く必要なかったんや・・・

Composer


composer require laravelcollective/html

View


{{ Form::open(['method' => 'POST', 'action' => 'HogeController@fuga']) }}
    {{ Form::submit() }}
    <ul>
    @foreach($items as $item)
        <li>
          {{ Form::checkbox('item_ids[]', $item->id) }}
        </li>
    @endforeach
    </ul>

    {{-- バリデーションエラー確認用 --}}
    @if ($errors->any())
        <div class="alert alert-danger">
            <ul>
                @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                @endforeach
            </ul>
        </div>
    @endif
{{ Form::close() }}

Controller


public function fuga(Request $request) {
    $this->validate($request, [
        'item_ids' => 'required|array',
        'item_ids.*' => 'email' // わざとバリデーションをエラーにして確認
    ]);
    dd($request->item_ids);
}

余談

もちろん、Formファサードを使用しない以下のコードはcheckedされません。


<input type="checkbox" name="item_ids[]" value="{{ $item->id }}">
0
1
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
0
1