With Livewire, you can easily build active interfaces with Laravel. You do not need to write any Javascript code. In this article, I share the livewire component’s code extracts.
Developers can easily create dynamic UIs using Livewire without having to write any Javascript. There are a variety of actions that can be performed without reloading the page, including like-dislike, comment, change password, login model, to-do list, toggle-switch, country state select, and update user.
Any web application built using Livewire works smoothly.
Here are the Livewire Components examples with code.
Change Password (Livewire Component Class)
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
class ChangePassword extends Component
{
public string $currentPassword = '';
public string $newPassword = '';
public string $newPassword_confirmation = '';
public function render()
{
return view('livewire.change-password');
}
protected $rules = [
'currentPassword' => 'required',
'newPassword' => 'required|string|min:6|confirmed',
];
public function updatePassword(){
$this->validate();
if (!(Hash::check($this->currentPassword, Auth::user()->password))) {
// The passwords matches
session()->flash('error', 'Your current password does not match.');
}
//Change Password
$user = Auth::user();
$user->password = bcrypt($this->newPassword);
$user->save();
session()->flash('success', 'Password updated successfully.');
$this->reset();
}
}
<div class="card card-bleed shadow-light-lg mb-6 border-0" id="changePassword">
<div class="card-header bg-white text-gray-700 py-4">
<div class="row align-items-center">
<div class="col">
<!-- Heading -->
<h5 class="mb-0">
Change Password
</h5>
</div>
</div>
</div>
<div class="card-body">
@if (session()->has('error'))
<div class="alert alert-danger">
{{ session('error') }}
</div>
@endif
@if (session()->has('success'))
<div class="alert alert-success">
{{ session('success') }}
</div>
@endif
<form wire:submit.prevent="updatePassword">
<!-- Current password -->
<div class="form-group mb-3">
<label class="form-label" for="currentPassword">Current Password</label>
<input class="form-control p-2 @error('currentPassword') is-invalid @enderror" id="currentPassword" type="password" wire:model="currentPassword">
@error('currentPassword')
<div class="invalid-feedback">
{{$message}}
</div>
@enderror
</div>
<!-- New password -->
<div class="form-group mb-3">
<label class="form-label" for="newPassword">New Password</label>
<input class="form-control p-2 @error('newPassword') is-invalid @enderror" id="newPassword" type="password" wire:model="newPassword">
@error('newPassword')
<div class="invalid-feedback">
{{$message}}
</div>
@enderror
</div>
<!-- Confirm password -->
<div class="form-group mb-3">
<label class="form-label" for="confirmPassword">Confirm Password</label>
<input class="form-control p-2" id="confirmPassword" type="password" wire:model="newPassword_confirmation">
</div>
<div class="row">
<div class="col-12 col-md-auto mt-3">
<!-- Button -->
<button class="btn w-100 btn-primary text-white" type="submit">
Update Password
</button>
</div>
</div>
</form>
</div>
</div>
The above code block is the implementation logic of a Livewire component called ChangePassword.
1. The render() method returns the view associated with the component, which is livewire.change-password.
2. Defined the public property $currentPassword, $newPassword, $newPassword_confirmation.
3. Defined the Protected property $rules in which we set the validation rules.
3. One method updatePassword – In this method, we check the current password, if the current password does not match we flash the error message else we reset the password.
4. The second code section is the Blade template of the change-password component.
5. The simple change password form. 3 new input fields, Current Password, New Password, New Password Confirmation, and update password submit button.
More livewire components example code can be found below.
ToDoList
<?php
namespace App\Http\Livewire;
use Carbon\Carbon;
use Livewire\Component;
use App\Models\DummyTask;
class ToDoList extends Component
{
public string $taskTitle = '';
public ?DummyTask $editing;
//public $tasks;
protected $rules=[
'taskTitle' => 'required|max:255',
'editing.title' => 'required|string|min:6',
];
public function mount()
{
//$this->tasks = DummyTask::orderBy('created_at','desc')->get();
}
public function render()
{
return view('livewire.to-do-list', [
'tasks' => DummyTask::orderBy('completed_at', 'asc')->orderBy('created_at','desc')->get()
]);
}
public function addTask(){
$this->validateOnly('taskTitle');
DummyTask::create([
'title' => $this->taskTitle
]);
$this->reset('taskTitle');
}
public function updateTaskStatus(DummyTask $task){
$task->completed_at = isset($task->completed_at) ? null : Carbon::now();
$task->save();
}
public function deleteTask(DummyTask $task){
$task->delete();
}
public function selectTaskForEdit(DummyTask $task){
$this->editing = $task;
}
public function cancelEdit(){
$this->editing = null;
}
public function updateTask(){
$this->validateOnly('editing.title');
$this->editing->save();
$this->editing = null;
}
}
//to-do-list.blade
<div>
<div class="row justify-content-center my-3">
<div class="col-md-10 bg-white border shadow py-3 px-5">
<div class="fw-bold fs-5 text-indigo my-3">Awesome ToDo List</div>
<div class="row">
<div class="col-md-12">
<div class="input-group mb-3">
<input type="text" class="form-control py-2 @error('taskTitle') is-invalid @enderror" wire:keydown.enter="addTask" placeholder="Whats needs to be done?" aria-label="taskTitle" wire:model="taskTitle">
<button class="btn bg-indigo text-white px-3 float-end" wire:click="addTask">Add</button>
@error('taskTitle')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<ul class="list-group list-group-flush">
@foreach($tasks as $task)
<li class="list-group-item" :wire:key="'task-details-'.$task->id">
<div class="d-flex justify-content-between align-items-end">
@if(isset($editing) && $editing->id == $task->id)
<div class="form-group flex-fill">
<input wire:key="editField" type="text" wire:keydown.enter="updateTask" class="form-control @error('editing.title') is-invalid @enderror" wire:model="editing.title"/>
@error('editing.title')
<div class="invalid-feedback">
{{ $message }}
</div>
@enderror
</div>
<div class="ms-3">
<i class="fas fa-save text-success cursor-pointer me-1" wire:click="updateTask()"></i>
<i class="fas fa-window-close text-secondary cursor-pointer" wire:click="cancelEdit()"></i>
</div>
@else
<div>
<input class="form-check-input me-1 p-2 align-sub" type="checkbox" {{isset($task->completed_at) ? 'checked' : ''}} value="1" wire:click="updateTaskStatus({{ $task->id }})">
<span class="{{isset($task->completed_at) ? 'text-decoration-line-through' : ''}}">{{$task->title}}</span>
</div>
<div>
<i class="fas fa-edit text-orange cursor-pointer me-1" wire:click="selectTaskForEdit({{ $task->id }})"></i>
<i class="fas fa-trash-alt text-danger cursor-pointer" wire:click="deleteTask({{ $task->id }})"></i>
</div>
@endif
</div>
</li>
@endforeach
</ul>
</div>
</div>
</div>
</div>
</div>
MultipleColorChoser
<?php
namespace App\Http\Livewire;
use Livewire\Component;
class MultipleColorChoser extends Component
{
public array $colorOptions = ['blue', 'red', 'pink', 'yellow', 'orange', 'dark', 'green', 'purple', 'white'];
public $colors = [];
public function render()
{
return view('livewire.multiple-color-choser');
}
public function clearColors(){
$this->colors = [];
}
}
//multiple-color-choser.blade.php
<div class="col-4">
<h5 class="text-gray-800 mt-4 mb-3 fw-bolder">Color @if(count($colors) > 0)<a wire:click="clearColors" class="fs-6 ms-2 cursor-pointer">clear</a>@endif</h5>
<div class="d-flex flex-wrap">
@foreach($colorOptions as $color)
<div class="{{$color}}-color me-2">
<input type="checkbox" class="btn-check" id="color-{{$color}}" value="{{$color}}" autocomplete="off" wire:model="colors">
<label for="color-{{$color}}">
<div class="bg-{{$color}} text-center pt-1 rounded-circle shadow {{ (in_array($color, $colors)) ? 'border border-dark' : ''}}" style="width:30px; height:30px">{!! (in_array($color, $colors)) ? '<i class="fas fa-check text-white"></i>' : '' !!}</div>
</label><br>
</div>
@endforeach
</div>
<div class="mt-5">You Chose {{implode(', ', $colors)}}</div>
</div>
Comment
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use Livewire\WithPagination;
use Illuminate\Support\Facades\Auth;
use Illuminate\Database\Eloquent\Model;
class Comment extends Component
{
use WithPagination;
protected $paginationTheme = 'bootstrap';
public Model $model;
public $user;
public string $newComment = '';
protected $rules = [
'newComment' => 'required|min:6',
];
public function render()
{
return view('livewire.comment', [
'comments' => $this->model->comments()->latest()->paginate(6),
]);
}
public function mount(){
$this->user = Auth::user();
}
public function postComment(){
if(!Auth::check())
return;
$this->validate();
$this->user->comment($this->model, $this->newComment);
$this->reset('newComment');
$this->model = $this->model->refresh();
}
}
#comment.blade.php
<div>
<div class="d-flex align-items-center justify-content-center bg-white py-3">
<div class="container">
<!-- Heading-->
<div class="row justify-content-center mb-4">
<div class="col-lg-12">
<h4 class="text-indigo">{{($model->totalCommentsCount() ? "{$model->totalCommentsCount()} Comments" : 'Comments')}}</h4>
</div>
</div>
<!-- Heading Ends -->
<!-- All Comments Section-->
<div class="row justify-content-center mb-4">
<div class="col-lg-12">
<div class="comments" wire:key="comments">
@forelse($comments as $comment)
<div class="comment d-flex mb-4" wire:key="{{$comment->id}}">
<div class="flex-shrink-0">
<div class="avatar avatar-sm">
<img class="avatar-img rounded-circle border" height="50" src="{{$comment->commented->avatarUrl()}}" alt="">
</div>
</div>
<div class="flex-grow-1 ms-2 ms-sm-3">
<div class="comment-meta d-flex align-items-baseline">
<h6 class="me-2">{{$comment->commented->name}}</h6>
<span class="text-muted">{{$comment->created_at->diffForHumans()}}</span>
</div>
<div class="comment-body text-wrap text-break">
{{$comment->comment}}
</div>
</div>
</div>
@empty
<div class="text-center">
<img src="/images/illustrations/comment.png" alt="no comments" height="400" class="mt-n5"/>
<p class="text-cyan fs-4"> It's so empty out here, go ahead and post some comments</p>
</div>
@endforelse
</div>
</div>
</div>
<!-- All Comments Section Ends-->
<!-- New Comment Section -->
@auth
<div class="row justify-content-center">
<div class="col-lg-12">
<div class="comment-form d-flex align-items-center">
<div class="flex-shrink-0 align-self-start">
<div class="avatar avatar-sm rounded-circle">
<img class="avatar-img rounded-circle border" height="50" src="{{auth()->user()->avatarUrl()}}" alt="">
</div>
</div>
<div class="flex-grow-1 ms-2 ms-sm-3">
<form wire:submit.prevent="postComment">
<textarea onkeyup="toggleButton(this,'bttnsubmit');" class="form-control py-0 px-1 border-0 @error('newComment') is-invalid @enderror" rows="2" placeholder="Start writing..." style="resize: none;" wire:model.lazy="newComment"></textarea>
@error('newComment')
<div class="invalid-feedback">
{{$message}}
</div>
@enderror
<button class="btn btn-sm bg-purple text-white mt-3" disabled='disabled' id='bttnsubmit'>Post</button>
</form>
</div>
</div>
</div>
</div>
@else
<button class="btn btn-sm btn-primary text-white mt-2" data-bs-toggle="modal" data-bs-target="#loginModal">Add Comment</button>
@endauth
<!-- New Comment Section Ends -->
<div class="mt-5">
{{ $comments->links() }}
</div>
</div>
</div>
</div>
<script>
function toggleButton(ref,bttnID){
document.getElementById(bttnID).disabled= ((ref.value !== ref.defaultValue) ? false : true);
}
</script>
CountryStateSelect
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use CountryState;
class CountryStateSelect extends Component
{
public array $countries;
public array $states = [];
public string $country = '';
public string $state = '';
public function render()
{
return view('livewire.country-state-select');
}
public function mount(){
$this->countries = CountryState::getCountries();
}
public function updatedCountry($value)
{
$this->state = '';
$this->states = CountryState::getStates($this->country);
}
}
#country-state-select.blade.php
<div>
<div class="mb-3">
<label for="country" class="form-label">Country</label>
<select class="form-select mb-3" aria-label="Country select box" wire:model="country">
<option selected>Select Country</option>
@foreach($countries as $countryKey => $countryValue)
<option value="{{$countryKey}}">{{$countryValue}}</option>
@endforeach
</select>
</div>
<div class="mb-3">
<label for="state" class="form-label">State</label>
<select class="form-select" aria-label="State select box" wire:model="state" wire:loading.attr="disabled" wire:target="country">
<option selected>Select State</option>
@foreach($states as $stateKey => $stateValue)
<option value="{{$stateKey}}">{{$stateValue}}</option>
@endforeach
</select>
</div>
</div>
Leave a Reply