In this tutorial, I’ll show you how to handle a click event in Laravel 11 Livewire 3 with a simple and clear example. If you're new to Livewire, don’t worry! I’ll explain everything step-by-step.
Livewire makes it super easy to handle JavaScript events like click, input, and submit directly in your Laravel Blade templates without writing any JavaScript code.
By the end of this tutorial, you'll be able to handle a click event using Livewire 3 in Laravel 11.
If you haven’t installed Laravel 11 yet, you can do so by running the following command:
composer create-project laravel/laravel laravel11-app
Now, let’s install Livewire 3 in your project:
composer require livewire/livewire
After that, publish the Livewire configuration file:
php artisan livewire:publish
Now let’s create a Livewire component using the artisan command:
php artisan make:livewire Counter
This command will generate two files:
Now open app/Livewire/Counter.php and update the logic like this:
app/Livewire/Counter.php
<?php
namespace App\Livewire;
use Livewire\Component;
class Counter extends Component
{
public $count = 0;
public function increment()
{
$this->count++;
}
public function render()
{
return view('livewire.counter');
}
}
Now open resources/views/livewire/counter.blade.php and update it like this:
resources/views/livewire/counter.blade.php
<div>
<h1>Counter: {{ $count }}</h1>
<button wire:click="increment">Click Me</button>
</div>
In the above code:
{{ $count }}
.wire:click
event that calls the increment
function from the component.
Now, include your component in the welcome.blade.php or any Blade file like this:
resources/views/welcome.blade.php
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Livewire Click Event</title>
@vite(['resources/css/app.css', 'resources/js/app.js'])
@livewireStyles
</head>
<body>
<livewire:counter />
@livewireScripts
</body>
</html>
Now, run your project using:
php artisan serve
You might also like:
In this article, we will see how to resize images before uploading in laravel 10. Here, we will learn about laravel 10&n...
Mar-29-2023
In this article, we will see how to send email using markdown mailable laravel 9. we will learn laravel 9 to s...
Aug-05-2022
In this article, we will see how to file upload in laravel 10 examples. Here, we will learn about the laravel...
Mar-15-2023
In this article, we will see how to focus on the next input when the max length is reached. Sometimes we have...
Aug-19-2020