In this tutorial, we will learn how to use laravel livewire when change event trigger. So that, let's start
Step-1: Install Laravel Livewire via composer
In this step, we need to install laravel livewire via composer command.
composer require livewire/livewire
Step-2: Create Component
We need to create component for change event via command
php artisan make:livewire changeEvent
This command will create two seperate files as
app/Http/Livewire/ChangeEvent.php
resources/views/livewire/change-event.blade.php
app/Http/Livewire/ChangeEvent.php
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class ChangeEvent extends Component
{
public $cities = [
1 => 'Dhaka',
2 => 'Delhi',
3 => 'Kualalampur'
];
public $city_id = '';
/**
* Write code on Method
*
* @return response()
*/
public function render()
{
return view('livewire.change-event')->extends('layouts.master');
}
/**
* Write code on Method
*
* @return response()
*/
public function changeEvent($value)
{
$this->city_id = $value;
}
}
resources/views/livewire/change-event.blade.php
<div>
<h1>Laravel Livewire Change Event Example - Web-tuts.com</h1>
<div>
<strong>Select City:</strong>
<select class="form-control" wire:click="changeEvent($event.target.value)">
<option value="">-- Select City --</option>
@foreach($cities as $key => $city)
<option value="{{ $key }}">{{ $city }}</option>
@endforeach
</select>
<p>Selected City ID: {{ $city_id }}</p>
</div>
</div>
Step-3 : Create Web Route
In this step, we need to create route for this change-event
routes/web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Livewire\ChangeEvent;
Route::get('change-event', ChangeEvent::class);
Step-4 : Create Views File
resources/views/layouts/app.blade.php
<!DOCTYPE html>
<html>
<head>
<title>Laravel Livewire Example - Kodersolution.com</title>
@livewireStyles
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
<script src="//maxcdn.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container">
@yield('content')
</div>
</body>
@livewireScripts
</html>
Finally, we are done. Now serve your application. Then go to browser and hit enter http://localhost:8000/change-event route.
Thanks for your time. Hope, it will help you in your future project.
Subscribe to the Email Newsletter