LoginSignup
21
15

More than 3 years have passed since last update.

Laravel5.7で動的チェックボックス(checkbox)のoldの操作について

Last updated at Posted at 2019-02-19

少しハマったのでチェックボックスの時のold操作でハマったので備忘録。そもそもLaravel側もメソッド用意してほしい

編集画面やエラー画面などで入力フォームの値を取得したい時oldヘルパーが便利ですよね。
こうするだけで入力フォームの値が取れるので重宝しています。

edit.blade/php
//前の入力画面の<input type="text" name="user">から値を取得
{{ old('user') }}

これを動的なタグのチェックボックスを使って試してみる
※テーブルの中身はidとnameの単純なもの

edit.blade.php
@foreach ($tags as $tag)
    <div class="form-check">
        <input type="checkbox" name="tag[]" id="tag{{ $loop->iteration }}" value="{{ $tag->id }}" @if (old('tag') == $loop->iteration) checked @endif>
        <label for="tag{{ $loop->iteration }}">{{ $tag->name }}</label>
    </div>
@endforeach

上記はtagのIDとforeachで回した時のカウント数が一致した時にcheckedを付けるという処理。
しかしこんなエラーが。。

htmlspecialchars() expects parameter 1 to be string, array given...

これは値が配列のために出るエラーですね。

調べたらすぐヒットしました!

edit.blade.php
<input type="checkbox" name="tag[]" id="tag{{ $loop->iteration }}" value="{{ $tag->id }}" @if (is_array(old("tag")) && in_array("1", old('tag'), true)) checked @endif>

ただこれだと"1"の部分が決めうちになってしまい、
今回のように動的な値のチェックボックスは全てにcheckedがついてしまう。

そこであまりスマートではないですが、"$tag->id"で文字列展開してください。
※ダブルクォーテーションを外すとint型になり一致しません。(oldは文字列のため)

edit.blade.php
<input type="checkbox" name="tag[]" id="tag{{ $loop->iteration }}" value="{{ $tag->id }}" @if (is_array(old("tag")) && in_array("$tag->id", old('tag'), true)) checked @endif>

2020.02.27追記
多分oldの型をint型にキャストした方がいいかも

edit.blade.php
<input type="checkbox" name="tag[]" id="tag{{ $loop->iteration }}" value="{{ $tag->id }}" @if (is_array(old("tag")) && in_array($tag->id, (int) old('tag'), true)) checked @endif>

2020.04.17追記
割と反応多い記事なので、最近よく使う三項演算子使って書き直す

edit.blade.php
<input type="checkbox" name="tag[]" id="tag{{ $loop->iteration }}" value="{{ $tag->id }}" {{ $tag->id === (int)old("tag") ? "checked" : '' }}>

これでイケるはず。

最後に

Laravel便利だけどもう少しbladeの自由度を高めてほしい。

21
15
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
21
15