Laravel Livewire is a full-stack framework for Laravel that simplifies the development of dynamic, modern web applications without needing to write a single line of JavaScript. With Livewire, you can build dynamic components using pure PHP, and it handles all the front-end interactions for you.
Think of Livewire as the bridge between your Laravel backend and a modern, interactive frontend. It provides a reactive and seamless user experience while reducing the complexity of integrating JavaScript frameworks like Vue or React.
Enhanced Performance: Livewire 3.0 introduces optimized rendering, making your components faster and more efficient.
Cleaner Syntax: Simplified syntax for defining properties, events, and methods.
Alpine.js 3.0 Integration: Livewire 3.0 works seamlessly with the latest version of Alpine.js.
New Lifecycle Hooks: Hooks like commit.prepare
and morph.updated
provide greater control over component behavior.
Navigate Functionality: Native support for SPA-like navigation without page reloads.
To use Livewire, you first need a Laravel application. Let’s create a new Laravel project:
composer create-project laravel/laravel livewire-example
Once the installation is complete, navigate to your project directory:
cd livewire-example
Next, install Livewire using Composer:
composer require livewire/livewire
After installation, you need to include Livewire’s assets in your Blade templates. Open the resources/views/welcome.blade.php
file and add the following lines inside the <head>
tag:
@livewireStyles
And before the closing <body>
tag, add:
@livewireScripts
These lines ensure that Livewire’s CSS and JavaScript assets are loaded.
Let’s create a simple Livewire component. Run the following Artisan command:
php artisan make:livewire Counter
This will create two new files:
app/Livewire/Counter.php
(PHP class for your component logic)
resources/views/livewire/counter.blade.php
(Blade template for your component UI)
Update the Counter.php
file with the following code:
count++;
}
public function render()
{
return view('livewire.counter');
}
}
Next, update the counter.blade.php
file:
Counter: {{ $count }}
You can now use your Livewire component in any Blade template. For example, in resources/views/welcome.blade.php
, add:
Start your local development server:
php artisan serve
Visit http://localhost:8000
, and you should see a counter component. Clicking the “Increment” button will update the counter in real time without refreshing the page.
When you interact with the Livewire component (e.g., clicking the button), a request is sent to the server.
Livewire processes the request, updates the component’s state, and re-renders the updated component on the page.
This happens asynchronously, ensuring a smooth and fast user experience.