Getting Started with Laravel Livewire
Today we’ll learn about Livewire. Let’s get stated:
Table of Contents
What is Livewire?
Livewire is a full-stack framework for Laravel that makes building dynamic interfaces simple, without leaving the comfort of Laravel. In some ways, we can consider Livewire as the replacement of Vue, React front-end in Laravel.
Have a look at the example:
Without refreshing page, the counter is working. We don’t need to write JavaScript code to do this kind of task.
Install Livewire
Run this command to install Livewire:
composer require livewire/livewire
Create a Component
Livewire works like Vue, React component. We’re able to use Livewire components in any blade file.
Let’s create a Livewire component named counter:
php artisan make:livewire counter
This command will create 2 files:
- app/Http/Livewire/Counter.php
- resources/views/livewire/counter.blade.php
Open Counter.php and paste this code:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class Counter extends Component
{
public $count = 0;
public function increment()
{
$this->count++;
}
public function decrement()
{
$this->count--;
}
public function render()
{
return view('livewire.counter');
}
}
Open counter.blade.php and paste this code:
<div>
<div class="d-flex justify-content-between">
<div class="p-2">
<button wire:click="increment" type="button" class="btn btn-info">+</button>
</div>
<div class="p-2">
<h1>{{ $count }}</h1>
</div>
<div class="p-2">
<button wire:click="decrement" type="button" class="btn btn-danger">-</button>
</div>
</div>
</div>
Our counter component is ready to use.
Use Component in Blade
In this step, we’ll use the counter component in blade file. Create a blade file called test.blade.php and import the livewire component like:
<head>
...
@livewireStyles
</head>
<body>
@livewire('counter')
...
@livewireScripts
</body>
</html>
The test blade file looks like:
<!DOCTYPE html>
<html>
<head>
<title>Laravel Livewire - MyNotePaper.com</title>
@livewireStyles
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
</head>
<body>
<div class="container" style="width: 750px; margin-top: 50px;">
<div class="card">
<div class="card-header text-center">
Laravel Livewire - MyNotePaper.com
</div>
<div class="card-body">
@livewire('counter')
</div>
</div>
</div>
@livewireScripts
<script src="{{ asset('js/app.js') }}"></script>
</body>
</html>
Define a route for the test blade file:
Route::get('/test', function () {
return view('test');
});
Now run the project and visit http://localhost:8000/test
route to see the output.
Md Obydullah
Software Engineer | Ethical Hacker & Cybersecurity...
Md Obydullah is a software engineer and full stack developer specialist at Laravel, Django, Vue.js, Node.js, Android, Linux Server, and Ethichal Hacking.