1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

【jsなし】Laravel でチェックボックス未選択時にデフォルト値(false)を使う

Last updated at Posted at 2019-11-12

checkboxは選択外した時にリクエストには含まれません。
調べたところhiddenにしjsで選択、非選択時に書き換えてそれを使うのを見ましたが、
Laravelならこれで出来そうっていうのがあったので、やってみます。

ミス、別の手法等がありましたら、ご指摘いただけますと幸いです。

view

まずはview側
普通に何個かチェックボックスがあるのみ

blade

<form action="{{route('test')}}" method="post">
    @csrf
    <input type="checkbox" value=1 name="c1">
    <input type="checkbox" value=1 name="c2">
    <input type="checkbox" value=1 name="c3">
</form>

Request

FormRequestを作成します。

php artisan make:request CheckRequest

作成したら、getValidatorInstanceをオーバーライドします。
送信されたものの値を優先するので、デフォルト側に上書きするようにmerge

CheckRequest.php
    
    protected function getValidatorInstance()
    {
        // デフォルト
        $default = [
            'c1' => 0,
            'c2' => 0,
            'c3' => 0,
        ];
        $data = array_merge($default,$this->all());

        $this->getInputSource()->replace($data);

        return parent::getValidatorInstance();
    }

dd($this->all(),$default,$data);
送信されたリクエスト、デフォルト、マージ後を出してみると下記のようになる。
c3は未選択なので送信されず、デフォルトのが使われています。
SC000010.JPG

あとは、バリデーションして登録するだけです。

1
0
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
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?