phplaravellaravel-livewirelaravel-livewire-wiremodel

Run livewire click method based on whether checkbox is checked or not


I'm new to livewire.

And I have Livewire component like below



<label for="active">Active:</label>



<input type="checkbox" id="active" wire:model.live="active" >Active

And component class have below code

class Advices extends Component
{
    public $advices, $text, $priority, $attached_day, $active, $advice_id;
    public $updateMode = false;
    public function render()
    {
        $this->advices = Advice::all();
        return view('livewire.advices');
    }
    private function resetInputFields(){
        $this->text='';
        $this->priority='';
        $this->attached_day='';
        $this->active='';
    }
    public function store()
    {
        $validator=$this->validate([
            'text'=>'bail|required',
            'priority'=>'nullable|integer',
            'attached_day'=>'nullable|integer|max:99',
            'active'=>'boolean'
        ]);
        $advice= new Advice();
        $advice->text= $this->text;
        $advice->priority= $this->priority ?? 1;
        $advice->attached_day = $this->attached_day ?? null;
        $advice->active= $this->active ?? true;
        $advice->timestamps = false;
        $advice->save();
        session()->flash('message','Advice Created Successfully.');
        $this->resetInputFields();
    }
    }

my requirements are that when the checkbox is clicked, the true value is sent, and when not clicked, the false value is sent

I meant that if the checkbox is checked, then "active"=true, if the checkbox is not checked, then "active"=false.

I don't want to use JS, so if you can give me a solution without JS I will be very happy.


Solution

  • The $active property must be a boolean (it's also validated as boolean in your code)

    So, the variable must be initialized as boolean, let's say true:

    public $active = true;
    

    then when you reset it, you must assign to it a boolean value not an empty string:

    
    private function resetInputFields()
    {
        .....
    
        $this->active = true;
    }
    

    Additional informations

    Initializing to true is just one example.
    If necessary, you can initialize the value to false instead.
    If you have an initial value read from a persistent storage (like a DB) you can initialize the variable in the mount() method which acts like a __construct() (see here for details).

    For example:

    public function mount()
    {
        $data = MyModel::first();
        .....
        $this->active = $data->active;
        .....
    }
    

    and probably you need to add a cast in your model:

    protected $casts = [
       'active' => 'boolean',
    ];
    

    Also, if you need, you can set the variable to false in the resetInputFields() method:

    private function resetInputFields(){
         $this->active = false;
    }