Laravel video tutorial: Discover Livewire
I suggest you discover together Livewire, a tool running on Laravel which will allow you to create dynamic components without using JavaScript.
What does it look like
First, we will create a class that will represent our component and its state. All the public properties of this component will be exposed and manipulated by the client and a method render ()
allows you to generate a new HTML version of the component.
use Livewire Component;
class SearchUsers extends Component
{
public $ search = '';
public function render ()
{
return view ('livewire.search-users', (
'users' => User :: where ('username', $ this-> search) -> get (),
));
}
}
Then in the view, it will be possible to use special attributes understood by livewire which will allow to communicate with our component.
@foreach ($ users as $ user)
- {{$ user-> username}}
@endforeach
Finally, we can now use the component in any page:
@livewire ('search-users')
...
When the user enters a search in the field, the view will automatically update to display only the users corresponding to the search.
How it works ?
Livewire relies primarily on the server to manage component state changes.
- Livewire renders the initial component with the page (like a simple template blade).
- During user interaction, livewire makes an AJAX call to the server with the data to update.
- The server renders the new HTML version of the component and sends it back to the client.
- Livewire receives the new HTML structure and modifies the DOM based on the elements that have changed.
However, this approach has a limitation important: Each interaction results in a round trip with the server. Also, you will have to pay attention to what you control with Livewire and use AlpineJS for micro-interactions that do not require server intervention.