Search code examples
laravellaravel-livewire

Get checkbox status in livewire


I have a form that has 2 checkboxes in this form. When I submit the information I want to test what the value of the first checkbox is. I use ‍‍‍‍‍‍`dd () but it shows me the value of Null. What is the problem? How can I solve this?

this is view:

<div class="form-group">
    <div class="custom-control custom-switch">
        <input class="custom-control-input" id="deposit" type="checkbox"> <label class="custom-control-label" for="deposit">Deposit</label>
    </div>
</div>
<div class="col-md-6">
    <div class="form-group">
        <div class="custom-control custom-switch">
            <input class="custom-control-input" id="withdraw" type="checkbox"> <label class="custom-control-label" for="withdraw">withdraw</label>
        </div>
    </div>
</div>
<button class="btn btn-round btn-outline-primary"><span class="w-100px">create</span></button>

and this is component:

<?php

namespace App\Http\Livewire\Backend\Currency;


use Livewire\Component;

class Networks extends Component
{
    
    public $deposit;
    public $withdraw;



    public function addNetwork()
    {
        dd($this->deposit1);
    }


    public function render()
    {
        return view('livewire.backend.currency.networks');
    }
}


Solution

  • You bind to the checkboxes like you would any other public property, using wire:model.

    <div class="form-group">
        <div class="custom-control custom-switch">
            <!-- bind to $deposit -->
            <input wire:model="deposit"
                    class="custom-control-input"
                    id="deposit"
                    type="checkbox">
            <label class="custom-control-label" for="deposit">Deposit</label>
        </div>
    </div>
    <div class="col-md-6">
        <div class="form-group">
            <div class="custom-control custom-switch">
                <!--bind to $withdraw -->
                <input wire:model="withdraw"
                        class="custom-control-input"
                        id="withdraw"
                        type="checkbox">
                <label class="custom-control-label" for="withdraw">withdraw</label>
            </div>
        </div>
    </div>
    
    

    Now when the form is submitted, if deposit or withdraw is checked, their value will be true.

    Something you might want to do is give $deposit and $withdraw a default value of false as otherwise their initial values will be null.

    public $deposit = false;
    
    public $withdraw = false;