Debug School

rakesh kumar
rakesh kumar

Posted on • Updated on

How liveware Optimized Rendering

To optimize rendering in a CRUD example using Laravel Livewire, we can utilize Livewire's ability to update only the specific components that are affected by user interactions. This means that when performing CRUD operations, only the relevant parts of the UI are updated without reloading the entire page. Let's build a simple optimized CRUD example:

Firstly, ensure you have Livewire installed in your Laravel project. If not, you can install it via Composer:

composer require livewire/livewire
Enter fullscreen mode Exit fullscreen mode

Now, let's create a Livewire component for managing items. Let's call it ItemManager.

php artisan make:livewire ItemManager
Enter fullscreen mode Exit fullscreen mode

This will generate a Livewire component in the 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()
    {
        $this->validate([
            'name' => 'required',
            'description' => 'required',
        ]);

        Item::create([
            'name' => $this->name,
            'description' => $this->description
        ]);

        $this->resetInputFields();
        $this->dispatch('itemCreated');
    }

    public function edit($id)
    {
        $item = Item::findOrFail($id);
        $this->itemId = $id;
        $this->name = $item->name;
        $this->description = $item->description;
    }

  public function update()
{
    $this->validate([
        'name' => 'required',
        'description' => 'required',
    ]);

    $item = Item::find($this->itemId);
    $item->update([
        'name' => $this->name,
        'description' => $this->description
    ]);

    $this->resetInputFields();
   $this->dispatch('itemUpdated', $item->fresh()->toArray());
}

    public function delete($id)
    {
        Item::find($id)->delete();
     $this->dispatch('itemDeleted');
    }

    private function resetInputFields()
    {
        $this->name = '';
        $this->description = '';
    }
}
Enter fullscreen mode Exit fullscreen mode

In item-manager.blade.php, let's create the view for the Livewire component:

<div>
    <input type="text" wire:model="name">
    @error('name') <span class="error">{{ $message }}</span> @enderror

    <input type="text" wire:model="description">
    @error('description') <span class="error">{{ $message }}</span> @enderror

    <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>
<!-- Modal -->
<div id="myModal" class="modal">
    <div class="modal-content">
        <!-- Updated item data will be displayed here -->
        <button class="close">Close</button>
    </div>
</div>
<script>
    document.addEventListener('DOMContentLoaded', function () {
        Livewire.on('itemCreated', function () {
           $('#myModal').show();
        });

      Livewire.on('itemUpdated', function (updatedItemData) {
            // Display updated item data in a popup modal
            $('#myModal .modal-content').html(`
                <p>Name: ${updatedItemData.name}</p>
                <p>Description: ${updatedItemData.description}</p>
                <button class="close">Close</button>
            `);
            $('#myModal').show();
        });

        Livewire.on('itemDeleted', function () {
           $('#myModal').show();
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

In Jquery

<script>
    $(document).ready(function () {
        Livewire.on('itemCreated', function () {
            $('#myModal').show();
        });

        Livewire.on('itemUpdated', function (updatedItemData) {
            // Display updated item data in a popup modal
            $('#myModal .modal-content').html(`
                <p>Name: ${updatedItemData.name}</p>
                <p>Description: ${updatedItemData.description}</p>
                <button class="close">Close</button>
            `);
            $('#myModal').show();
        });

        Livewire.on('itemDeleted', function () {
            $('#myModal').show();
        });

        // Close modal when close button is clicked
        $(document).on('click', '.close', function() {
            $('#myModal').hide();
        });

        // Close modal when user clicks outside of it
        $(document).on('click', function(event) {
            if (event.target == $('#myModal')[0]) {
                $('#myModal').hide();
            }
        });
    });
</script>
Enter fullscreen mode Exit fullscreen mode

In this optimized CRUD example, we utilize Livewire's ability to emit events after specific actions (itemCreated, itemUpdated, itemDeleted). We then listen to these events in JavaScript using Livewire's Livewire.on() method and perform any necessary updates or actions on the client-side. This approach ensures that only the relevant parts of the UI are updated when CRUD operations are performed, leading to optimized rendering and a smoother user experience. Additionally, we added form validation to ensure data integrity before performing CRUD operations.

Top comments (0)