Setting default content on Laravel Livewire @entangle

Mar 2023

I was having some trouble getting Livewire and Alpine to entangle with a default value. This is especially useful for dropdowns where you have the same thing 90% of the time but need the value coming from Livewire sometimes.

Here's what I did:

<div  x-data="{
        unit: @entangle("block.content.unit"),
        setDefaultUnit() {
            if(!this.unit) {
                this.unit= 'px'
            }
        }
    }" x-init="setDefaultUnit()">

This checks to see if there's a default unit and then sets it (hardcoded to 'px') in this case.