Laravel Livewire 2.0 was released a couple of months ago with some really cool features 🙌. One of which is the ability to share variable data between Livewire and Alpine!
This is a really cool feature because it's as if your PHP variables can now be used as javascript variables in Alpine.
How does it work
By utilizing the new @entangle
feature we can now share a PHP variable with our Alpine JS data like so:
<div x-data="{ visible : @entangle('isVisible') }">
<p x-show="visible">Awesome!</p>
</div>
Notice that the <p>
above will only be visible if the value of visible
is set to true.
Using the @entangle
function, we are retrieving and sharing the value of the isVisible
PHP variable inside of the Livewire component controller.
class ComponentName extends Component
{
public $isVisible = false;
public function setVisibleTrue()
{
$this->isVisible = true;
}
}
How awesome is that? We could then add a button in our Alpine component to call our setVisibleTrue()
function.
<div x-data="{ visible : @entangle('isVisible') }">
<p x-show="visible">Awesome!</p>
<button wire:click="setVisibleTrue()">Show</button>
</div>
Or, we could always use a magic function to set the isVisible
to true
like so:
<button wire:click="$set('isVisible', true)">Show</button>
Even better we could change the PHP variable by setting the Alpine visible
variable to true:
<button @click="visible = true">Show</button>
As you can see, when we change the visible
value in our Alpine component, it automatically shares state with our PHP variable and sets $isVisible
to true
🤯
Learning More
Be sure to visit the Livewire docs on sharing data with Alpine here: https://laravel-livewire.com/docs/2.x/alpine-js. You can utilize so many cool features to make interacting with Alpine and Livewire data as seamless as can be.
Conclusion
The ability to share state between PHP and javascript opens up a wide array of possibilities. Creating dynamic web applications is now easier than ever, thanks to the awesomeness of Livewire.
Be sure to check out the screencasts provided by the creator of Livewire to learn all the cool stuff you can do with this library.