Livewire simple dropdown and save button with model property binding

Viewed 1749

In my view I have:

<form wire:submit.prevent="save">

    <select wire:model.defer="post.is_public">
        <option value="0">No</option>
        <option value="1">Yes</option>
    </select>

    <button type="submit">
        Submit
    </button>
    
</form>

And in the component:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Post;

class PostPublicToggle extends Component
{
    public Post $post;

    protected $rules = [
        'post.is_public' => 'boolean'
    ];

    public function render()
    {
        return view('livewire.post-public-toggle');
    }

    public function save()
    {
        $this->validate();
        $this->post->save();
    }
}

First I wanted this to work without a submit button (auto-submit on select change). But that didn't work so that's why I added .defer and a submit button.

Now when I press submit, I can see in the XHR request that post.is_public = null and I don't understand why.

0 Answers
Related