Best three ways to lower server requests with Laravel Livewire

Categorized as Laravel, Livewire Tagged ,

One of the first questions they have for people who get started with Livewire is why there are so many separate requests to the server. As you may know, with a change on the Livewire model field, there’s an ajax request or API request. And there are just too many requests to load on the server. So, for example, if we click something in the input field, there’s a separate request, and there’s an API request on any change. And that’s pretty bad.

So that default behavior is good if you have any Livewire validation or live changing data, but there are a few things that you can do to avoid so many requests.

First, let’s talk about Debounce.

Debounce is the parameter of the small amount of time when the request happens. By default, it’s 150 milliseconds. So if you do multiple events (pressing the button many times fast or typing in some input), there will be no more than one event sent to the server in 150 ms.

<input type="text" wire:model.debounce.1000ms="name">
 
<!-- You can also specify the time in seconds: -->
<input type="text" wire:model.debounce.1s="name">

The second way to lower the number of requests is doing the server request not on the change of the value or not on typing, but only when the field is left. And it is called model Lazy.

We can deliver all the changes with no requests, but when we click a Tab and leave it to the second field of the form, the requests are happening. That’s probably the most typical scenario, and we would probably advise you to use model lazy every time unless you actually need the live validation.

class MyNameIs extends Component
{
    public $name;
}
<div>
    <input type="text" wire:model.lazy="name">
 
    My name is Toca Boca {{ $name }}
</div>

The third thing you can do is model Defer. Defer means that it will save the value internally in Livewire and pass it only on the following network request. So whatever any network requests happening next, that value will be updated with that request.

So if you’re doing any live validation or any actions before submitting the form, the best way is to do Livewire model defer, and that data will be updated only on submit.

<input type="text" wire:model.defer="query">
<button wire:click="search">Search</button>

So those are three ways to make fewer requests to the server with Livewire.

Leave a reply

Your email address will not be published. Required fields are marked *