Calling Livewire methods from Alpine.js

April 23rd, 2024 • 2 minutes read time

Because Livewire and Alpine.js are so tightly linked, calling a Livewire method from your Alpine components is a breeze.

We'll also dive into some other handy tips — because sometimes, you don't need a method!

Take the following example of a simple Comments component.

class Comments extends Component
{
    public function render()
    {
        return view('livewire.comments');
    }
}

The corresponding template looks like this right now.

<form>
    <textarea placeholder="Write a comment"></textarea>
</form>

Our goal is to invoke a Livewire method when the user hits return within this textarea.

A keyup event isn't something we'd usually be able to handle with Livewire in a Blade template, so let's update this to call the Livewire method on a keyup event.

<form>
    <textarea x-on:keyup.enter="$wire.storeComment()" wire:model="body" placeholder="Write a comment"></textarea>
</form>

The method doesn't need any special, it's just a normal Livewire method.

class Comments extends Component
{
    public string $body;
    
    public function storeComment()
    {
        // store the comment    
    }
    
    public function render()
    {
        return view('livewire.comments');
    }
}

And that's it! With $wire you're able to call any method on your Livewire component.

If you need to access or mutate properties, or refresh a component — there's no need to add an extra method to your component.

Here's a contrived example of setting a property on a component using Alpine.js.

class Hover extends Component
{
    public string $hovered;
    
    public function render()
    {
        return view('livewire.hover');
    }
}

And here's the template that updates a property directly from Alpine.js.

<div>
    @if ($hovered)
    	<div>You hovered!</div>
    @endif

    <button x-on:mouseover="$wire.hovered = true">Hover over me</button>
</div>

There are a few other examples over on the Livewire documentation and they're worth checking out for future!

Because Livewire and Alpine.js are so interlinked, calling a method (among other things) is super simple.

If you found this article helpful, you'll love our practical screencasts.
Author
Alex Garrett-Smith
Share :

Comments

No comments, yet. Be the first!