Here's a simple CRUD (Create, Read, Update, Delete) example using Laravel Livewire to reduce server calls. Livewire is a Laravel framework for building dynamic interfaces without leaving the comfort of Laravel.
Firstly, make sure you have Livewire installed in your Laravel project. If not, you can install it via Composer:
composer require livewire/livewire
Now, let's create a basic Livewire component for managing items. Let's call it ItemManager.
php artisan make:livewire ItemManager
This will generate a Livewire component in App/Http/Livewire directory. You'll find two files: item-manager.php and item-manager.blade.php.
In item-manager.php, let's define the CRUD operations:
<?php
namespace App\Http\Livewire;
use Livewire\Component;
use App\Models\Item;
class ItemManager extends Component
{
public $items, $name, $description, $itemId;
public function render()
{
$this->items = Item::all();
return view('livewire.item-manager');
}
public function create()
{
Item::create([
'name' => $this->name,
'description' => $this->description
]);
$this->resetInputFields();
}
public function edit($id)
{
$item = Item::findOrFail($id);
$this->itemId = $id;
$this->name = $item->name;
$this->description = $item->description;
}
public function update()
{
$item = Item::find($this->itemId);
$item->update([
'name' => $this->name,
'description' => $this->description
]);
$this->resetInputFields();
}
public function delete($id)
{
Item::find($id)->delete();
}
private function resetInputFields()
{
$this->name = '';
$this->description = '';
}
}
In item-manager.blade.php, let's create the view for the Livewire component:
<div>
<input type="text" wire:model="name">
<input type="text" wire:model="description">
<button wire:click="create">Create</button>
@if($items->count())
<ul>
@foreach($items as $item)
<li>
{{ $item->name }} - {{ $item->description }}
<button wire:click="edit({{ $item->id }})">Edit</button>
<button wire:click="delete({{ $item->id }})">Delete</button>
</li>
@endforeach
</ul>
@else
<p>No items found</p>
@endif
</div>
In this example, we bind input fields to Livewire properties using wire:model. When the user types something into the input fields, the corresponding Livewire properties ($name and $description) are updated automatically.
When the "Create" button is clicked, the create method is called, which creates a new item in the database and resets the input fields.
The "Edit" button calls the edit method, which populates the input fields with the details of the item to be edited.
The "Update" button (not shown in the UI for brevity) would call the update method to update the item in the database.
The "Delete" button calls the delete method to delete the item from the database.
This Livewire component ensures that only necessary data is sent back and forth between the server and the client, reducing unnecessary server calls.
Top comments (0)