![Laravel Livewire Using wire_model On Custom Component and x-modelable](https://webmobtuts.com/wp-content/uploads/2024/04/Laravel-Livewire-Using-wire_model-On-Custom-Component-and-x-modelable-800x400.jpg)
In laravel livewire 3 you can assign wire:model attribute on custom components to take the advantage of data binding on custom components.
As we know that Laravel livewire is all about creating components, you can extract every piece of your application into a component to make it work independently. Also one of the common tasks in web applications is manipulating forms.
In laravel livewire we can use data binding on html inputs using the wire:model directive. The wire:model directive can be used on every html inputs. However it can also be used in combination with Alpinejs on custom components.
To illustrate this imagine we have a laravel project with livewire installed. we have a form component to enter product amount.
app/Livewire/ProductForm.php
<?php namespace App\Livewire; use Livewire\Component; class ProductForm extends Component { public $amount = 100; public function render() { return view('livewire.product-form'); } }
resources/views/livewire/custom-control.blade.php
<div> <input type="text" wire:model="amount" /> </div>
This is simple livewire component with single html input. Our target is to to extract thsi input into separate component with the ability to increment or decrement the amount.
To do this we will create a laravel component and using Alpinejs beside livewire.
resources/views/components/number-input.blade.php
<div x-data="{ count: 0 }" x-modelable="count" {{ $attributes}}> <span x-on:click="count++">+</span> <input type="text" x-model="count" style="text-align: center" /> <span x-on:click="count--">-</span> <div style="margin-top: 20px">Amount: <span x-html="count"></span></div> </div>
In this code i added a div that wraps an input and two buttons to increment and decrement the count. Notice the directives x-data, x-model, x-html, etc. These are Alpinejs directives.
We initialized the count property in our div using x-data directive. This way the entire div has access to the count property using x-model or x-html. Whenever you type in the input it will reflect in the x-html.
When clicking on any of the two span elements it will increment or decrement the count using the x-on:click directive respectively.
Now replace the html input in the ProductForm component with the new component like so:
<x-number-input wire:model="amount" />
This is how you call laravel components. If you try this you will see it working.
How the wire:model is working on the custom component. The secret is the x-modelable directive. The x-modelable directive allows the interaction between livewire wire:model on the root component and Alpinejs. You can learn more about it here.
Also it’s important to pass {{ $attributes }} as shown above so that any other attributes on the <x-number-input /> can be forwarded.