You're browsing the documentation for an old version of Livewire. Consider upgrading your project to Livewire 3.x.

AlpineJS

Be amazing at Livewire
with our in-depth screencasts.
Watch Now

There are lots of instances where a page interaction doesn't warrant a full server-roundtrip, like toggling a modal.

For these cases, AlpineJS is the perfect companion to Livewire.

It allows you to sprinkle JavaScript behavior directly into your markup in a declarative/reactive way that should feel very similar to VueJS (If that's what you're used to).

Installation

You must install Alpine in order to use it with Livewire.

To install Alpine in your project, add the following script tag to the <head> section of your layout file.

        
1<head>
2 ...
3 <script defer src="https://unpkg.com/[email protected]/dist/cdn.min.js"></script>
4 <!-- The "defer" attribute is important to make sure Alpine waits for Livewire to load first. -->
5</head>

For more installation information, visit the Alpine Docs.

Using Alpine Inside Of Livewire

Here's an example of using AlpineJS for "dropdown" functionality INSIDE a Livewire component's view.

        
1<div>
2 ...
3 
4 <div x-data="{ open: false }">
5 <button @click="open = true">Show More...</button>
6 
7 <ul x-show="open" @click.outside="open = false">
8 <li><button wire:click="archive">Archive</button></li>
9 <li><button wire:click="delete">Delete</button></li>
10 </ul>
11 </div>
12</div>

Extracting Reusable Blade Components

If you are not already used to each tool on its own, mixing the syntaxes of both can be a bit confusing.

Because of this, when possible, you should extract the Alpine parts to reusable Blade components for consumption inside of Livewire (and anywhere in your app).

Here is an example (Using Laravel 7 Blade component tag syntax).

The Livewire View:

        
1<div>
2 ...
3 
4 <x-dropdown>
5 <x-slot name="trigger">
6 <button>Show More...</button>
7 </x-slot>
8 
9 <ul>
10 <li><button wire:click="archive">Archive</button></li>
11 <li><button wire:click="delete">Delete</button></li>
12 </ul>
13 </x-dropdown>
14</div>

The Reusable "dropdown" Blade Component:

        
1<div x-data="{ open: false }">
2 <span @click="open = true">{{ $trigger }}</span>
3 
4 <div x-show="open" @click.outside="open = false">
5 {{ $slot }}
6 </div>
7</div>

Now, the Livewire and Alpine syntaxes are completely separate, AND you have a reusable Blade component to use from other components.

Interacting With Livewire From Alpine: $wire

From any Alpine component inside a Livewire component, you can access a magic $wire object to access and manipulate the Livewire component.

To demonstrate its usage, we'll create a "counter" component in Alpine that uses Livewire completely under the hood:

            
1class Counter extends Component
2{
3 public $count = 0;
4 
5 public function increment()
6 {
7 $this->count++;
8 }
9}
            
1<div>
2 <!-- Alpine Counter Component -->
3 <div x-data>
4 <h1 x-text="$wire.count"></h1>
5 
6 <button x-on:click="$wire.increment()">Increment</button>
7 </div>
8</div>

Now, when a user clicks "Increment", the standard Livewire round trip will trigger and Alpine will reflect Livewire's new $count value.

Because $wire uses a JavaScript Proxy under the hood, you are able to access properties on it and call methods on it and those operations will be forwarded to Livewire. In addition to this functionality, $wire also has standard, built-in methods available to you.

Here is the full API for $wire:

        
1// Accessing a Livewire property
2$wire.foo
3 
4// Calling a Livewire method
5$wire.someMethod(someParam)
6 
7// Calling a Livewire method and doing something with its result
8$wire.someMethod(someParam)
9 .then(result => { ... })
10 
11// Calling a Livewire method and storing its response using async/await
12let foo = await $wire.getFoo()
13 
14// Emitting a Livewire event called "some-event" with two parameters
15$wire.emit('some-event', 'foo', 'bar')
16 
17// Listening for a Livewire event emitted called "some-event"
18$wire.on('some-event', (foo, bar) => {})
19 
20// Getting a Livewire property
21$wire.get('property')
22 
23// Setting a Livewire property to a specific value
24$wire.set('property', value)
25 
26// Defer setting a Livewire property to a specific value
27$wire.set('property', value, true)
28 
29// Calling a Livewire action
30$wire.call('someMethod', param)
31 
32// Uploading file and setting Livewire property
33$wire.upload(
34 'property',
35 file,
36 finishCallback = (uploadedFilename) => {},
37 errorCallback = () => {},
38 progressCallback = (event) => {}
39)
40 
41// Uploading multiple files and setting Livewire property
42$wire.uploadMultiple(
43 'property',
44 files,
45 finishCallback = (uploadedFilenames) => {},
46 errorCallback = () => {},
47 progressCallback = (event) => {}
48)
49 
50// Removing (one of) uploaded file(s) and updating Livewire property
51$wire.removeUpload(
52 'property',
53 uploadedFilename,
54 finishCallback = (uploadedFilename) => {},
55 errorCallback = () => {}
56)
57 
58// Accessing the underlying Livewire component JavaScript instance
59$wire.__instance

Sharing State Between Livewire And Alpine: @entangle

Livewire has an incredibly powerful feature called "entangle" that allows you to "entangle" a Livewire and Alpine property together. With entanglement, when one value changes, the other will also be changed.

To demonstrate, consider the dropdown example from before, but now with its showDropdown property entangled between Livewire and Alpine. By using entanglement, we are now able to control the state of the dropdown from both Alpine AND Livewire.

            
1class Dropdown extends Component
2{
3 public $showDropdown = false;
4 
5 public function archive()
6 {
7 ...
8 $this->showDropdown = false;
9 }
10 
11 public function delete()
12 {
13 ...
14 $this->showDropdown = false;
15 }
16}
            
1<div x-data="{ open: @entangle('showDropdown') }">
2 <button @click="open = true">Show More...</button>
3 
4 <ul x-show="open" @click.outside="open = false">
5 <li><button wire:click="archive">Archive</button></li>
6 <li><button wire:click="delete">Delete</button></li>
7 </ul>
8</div>

Now a user can toggle on the dropdown immediately with Alpine, but when they click a Livewire action like "Archive", the dropdown will be told to close from Livewire. Both Alpine and Livewire are welcome to manipulate their respective properties, and the other will automatically update.

Sometimes, it isn't necessary to update Livewire on every Alpine change, and you'd rather bundle the change with the next Livewire request that goes out. In these cases, you can chain on a .defer property like so:

        
1<div x-data="{ open: @entangle('showDropdown').defer }">
2 ...

Now, when a user toggles the dropdown open and closed, there will be no AJAX requests sent for Livewire, HOWEVER, when a Livewire action is triggered from a button like "archive" or "delete", the new state of "showDropdown" will be bundled along with the request.

If you are having trouble following this difference. Open your browser's devtools and observe the difference in XHR requests with and without .defer added.

Using the @js directive

If ever you need to output PHP data for use in Alpine, you can now use the @js directive.

        
1<div x-data="{ posts: @js($posts) }">
2 ...
3</div>

Accessing Livewire Directives From Blade Components

Extracting re-usable Blade components within your Livewire application is an essential pattern.

One difficulty you might encounter while implementing Blade components within a Livewire context is accessing the value of attributes like wire:model from inside the component.

For example, you might create a text input Blade component like so:

        
1<!-- Usage -->
2<x-inputs.text wire:model="foo"/>
3 
4<!-- Definition -->
5<div>
6 <input type="text" {{ $attributes }}>
7</div>

A simple Blade component like this will work perfectly fine. Laravel and Blade will automatically forward any extra attributes added to the component (like wire:model in this case), and place them on the <input> tag because we echoed out the attribute bag ($attributes).

However, sometimes you might need to extract more detailed information about Livewire attributes passed to the component.

For these cases, Livewire offers an $attributes->wire() method to help with these tasks.

Given the following Blade Component usage:

        
1<x-inputs.text wire:model.defer="foo" wire:loading.class="opacity-25"/>

You could access Livewire directive information from Blade's $attribute bag like so:

        
1$attributes->wire('model')->value(); // "foo"
2$attributes->wire('model')->modifiers(); // ["defer"]
3$attributes->wire('model')->hasModifier('defer'); // true
4 
5$attributes->wire('loading')->hasModifier('class'); // true
6$attributes->wire('loading')->value(); // "opacity-25"

You can also "forward" these Livewire directives individually. For example:

        
1<!-- Given -->
2<x-inputs.text wire:model.defer="foo" wire:loading.class="opacity-25"/>
3 
4<!-- You could forward the "wire:model.defer="foo" directive like so: -->
5<input type="text" {{ $attributes->wire('model') }}>
6 
7<!-- The output would be: -->
8<input type="text" wire:model.defer="foo">

There are LOTS of different ways to use this utility, but one common example is using it in conjunction with the aforementioned @entangle directive:

        
1<!-- Usage -->
2<x-dropdown wire:model="show">
3 <x-slot name="trigger">
4 <button>Show</button>
5 </x-slot>
6 
7 Dropdown Contents
8</x-dropdown>
9 
10<!-- Definition -->
11<div x-data="{ open: @entangle($attributes->wire('model')) }">
12 <span @click="open = true">{{ $trigger }}</span>
13 
14 <div x-show="open" @click.outside="open = false">
15 {{ $slot }}
16 </div>
17</div>

Note: If the .defer modifier is passed via wire:model.defer, the @entangle directive will automatically recognize it and add the @entangle('...').defer modifier under the hood.

Creating A DatePicker Component

A common use case for JavaScript inside Livewire is custom form inputs. Things like datepickers, color-pickers, etc... are often essential to your app.

By using the same pattern above, (and adding some extra sauce), we can utilize Alpine to make interacting with these types of JavaScript components a breeze.

Let's create a re-usable Blade component called date-picker that we can use to bind some data to in Livewire using wire:model.

Here's how we will be using it:

        
1<form wire:submit.prevent="schedule">
2 <label for="title">Event Title</label>
3 <input wire:model="title" id="title" type="text">
4 
5 <label for="date">Event Date</label>
6 <x-date-picker wire:model="date" id="date"/>
7 
8 <button>Schedule Event</button>
9</form>

For this component we will be using the Pikaday library.

According to the docs, the most basic usage of the package (after including the assets) looks like this:

        
1<input type="text" id="datepicker">
2 
3<script>
4 new Pikaday({ field: document.getElementById('datepicker') })
5</script>

All you need is an <input> element, and Pikaday will add all the extra date-picker behavior for you.

Now let's see how we might write a re-usable Blade component for this library.

The date-picker Reusable Blade Component:

        
1<input
2 x-data
3 x-ref="input"
4 x-init="new Pikaday({ field: $refs.input })"
5 type="text"
6 {{ $attributes }}
7>

Note: The {{ $attributes }} expression is a mechanism in Laravel 7 and above to forward extra HTML attributes declared on the component tag.

Forwarding wire:model input Events

Under the hood, wire:model adds an event listener to update a property every time the input event is dispatched on or under the element. Another way to communicate between Livewire and Alpine is by using Alpine to dispatch an input event with some data within or on an element with wire:model on it.

Let's create a contrived example where when a user clicks the first button a property called $foo is set to bar, and when a user clicks the second button, $foo is set to baz.

Within A Livewire Component's View:

        
1<div>
2 <div wire:model="foo">
3 <button x-data @click="$dispatch('input', 'bar')">Set to "bar"</button>
4 <button x-data @click="$dispatch('input', 'baz')">Set to "baz"</button>
5 </div>
6</div>

A more real-world example would be creating a "color-picker" Blade component that might be consumed inside a Livewire component.

Color-picker Component Usage:

        
1<div>
2 <x-color-picker wire:model="color"/>
3</div>

For the component definition, we will be using a third-party color-picker lib called Vanilla Picker.

This sample assumes you have it loaded on the page.

Color-picker Blade Component Definition (Un-commented):

        
1<div
2 x-data="{ color: '#ffffff' }"
3 x-init="
4 picker = new Picker($refs.button);
5 picker.onDone = rawColor => {
6 color = rawColor.hex;
7 $dispatch('input', color)
8 }
9 "
10 wire:ignore
11 {{ $attributes }}
12>
13 <span x-text="color" :style="`background: ${color}`"></span>
14 <button x-ref="button">Change</button>
15</div>

Color-picker Blade Component Definition (Commented):

        
1<div
2 x-data="{ color: '#ffffff' }"
3 x-init="
4 // Wire up to show the picker when clicking the 'Change' button.
5 picker = new Picker($refs.button);
6 // Run this callback every time a new color is picked.
7 picker.onDone = rawColor => {
8 // Set the Alpine 'color' property.
9 color = rawColor.hex;
10 // Dispatch the color property for 'wire:model' to pick up.
11 $dispatch('input', color)
12 }
13 "
14 // Vanilla Picker will attach its own DOM inside this element, so we need to
15 // add `wire:ignore` to tell Livewire to skip DOM-diffing for it.
16 wire:ignore
17 // Forward the any attributes added to the component tag like `wire:model=color`
18 {{ $attributes }}
19>
20 <!-- Show the current color value with the backgound color set to the chosen color. -->
21 <span x-text="color" :style="`background: ${color}`"></span>
22 <!-- When this button is clicked, the color-picker dialogue is shown. -->
23 <button x-ref="button">Change</button>
24</div>

Ignoring DOM-changes (using wire:ignore)

Fortunately a library like Pikaday adds its extra DOM at the end of the page. Many other libraries manipulate the DOM as soon as they are initialized and continue to mutate the DOM as you interact with them.

When this happens, it's hard for Livewire to keep track of what DOM manipulations you want to preserve on component updates, and which you want to discard.

To tell Livewire to ignore changes to a subset of HTML within your component, you can add the wire:ignore directive.

The Select2 library is one of those libraries that takes over its portion of the DOM (it replaces your <select> tag with lots of custom markup).

Here is an example of using the Select2 library inside a Livewire component to demonstrate the usage of wire:ignore.

        
1<div>
2 <div wire:ignore>
3 <select class="select2" name="state">
4 <option value="AL">Alabama</option>
5 <option value="WY">Wyoming</option>
6 </select>
7 
8 <!-- Select2 will insert its DOM here. -->
9 </div>
10</div>
11 
12@push('scripts')
13<script>
14 $(document).ready(function() {
15 $('.select2').select2();
16 });
17</script>
18@endpush
Also, note that sometimes it's useful to ignore changes to an element, but not its children. If this is the case, you can add the self modifier to the wire:ignore directive, like so: wire:ignore.self.
← Previous Topic Defer Loading
Next Topic → Laravel Echo