skip to Main Content

I have difficulty how to save the checkboxes on to the database using livewire.

view:

<div class="mt-2">
<div class="flex items-center space-x-8 justify-center">
    <label for="Email"> Email</label>
    <input type="checkbox" value="{{$notificationEmail}}" id="notification_email" wire:model="notificationEmail">

    <label for="Phone"> Phone Number</label>
    <input type="checkbox" value="{{$notificationPhone}}" id="notification_phone" wire:model="notificationPhone">

    <label for="WhatsApp"> WhatsApp</label>
    <input type="checkbox" value="{{$notificationWhatsapp}}" id="notification_whatsapp" wire:model="notificationWhatsapp">

</div>
<span>Email : {{ var_export($notificationEmail) }}</span>
<span>Phone : {{ var_export($notificationPhone) }}</span>
<span>WhatsApp : {{ var_export($notificationWhatsapp) }}</span>

mount:

public $notificationEmail = false;
public $notificationPhone = false;
public $notificationWhatsapp = false;

public function mount()
{
    $this->user = User::find(Auth::id());
    $this->notificationEmail = $this->user->notification_email;
    $this->notificationPhone = $this->user->notification_phone;
    $this->notificationWhatsapp = $this->user->notification_whatsapp;
}

submit function:

public function submitNotifications(Request $request)
{

    // Close modal
    $this->dispatchBrowserEvent('close-modal');

    $this->dispatchBrowserEvent('notify', ['type' => 'success', 'message' => 'Account Settings changed!']);

    User::find($this->user->id)->update([
        'notification_email' => $this->notificationEmail,
        'notification_phone' => $this->notificationPhone,
        'notification_whatsapp' => $this->notificationWhatsapp
    ]);


}

I just want to know why it is not saving on my database after I checked/ticked on of those options.

Appreciate the help. Beginner here. Thanks

2

Answers


  1. You can convert data into boolean by defining data type like this

    User::find($this->user->id)->update([
        'notification_email' => (bool)$this->notificationEmail,
        'notification_phone' => (bool)$this->notificationPhone,
        'notification_whatsapp' => (bool)$this->notificationWhatsapp
    ]);
    
    Login or Signup to reply.
  2. just add:

    protected  $casts = [
        'notification_email' => 'boolean',
        'notification_phone' => 'boolean',
        'notification_whatsapp' => 'boolean'
    ];
    

    to your Livewire Component

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search