Engaging the Reader with Laravel Livewire code

Laravel  Livewire realtime practical with new process

laravel
Laravel Schema 3 months ago · 3 min read
Engaging the Reader with Laravel Livewire code

Engaging the Reader with Laravel Livewire Code

Showcasing practical examples is the best way to illustrate the power of Laravel Livewire. Let's consider a scenario where you need to create a dynamic to-do list. With Livewire, this becomes remarkably straightforward.

Setting up the To-Do List Component

Create a new Livewire component for the to-do list:

php artisan make:livewire ToDoList

Open the generated ToDoList.php file and define the component logic. Add a property to store the list of tasks:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class ToDoList extends Component
{
    public $tasks = [];

    public function render()
    {
        return view('livewire.todo-list');
    }
}

Creating the Blade View

Open the Blade view file (resources/views/livewire/todo-list.blade.php) and add the following code:

<div>
    <h1>My To-Do List</h1>

    <ul>
        @foreach($tasks as $task)
            <li>{{ $task }}</li>
        @endforeach
    </ul>
</div>

This code displays a simple to-do list.

Making it Interactive

Now, let's add interactivity. Update the ToDoList.php file to include methods for adding and removing tasks:

<?php

namespace App\Http\Livewire;

use Livewire\Component;

class ToDoList extends Component
{
    public $tasks = [];
    public $newTask;

    public function addTask()
    {
        $this->tasks[] = $this->newTask;
        $this->newTask = '';
    }

    public function removeTask($index)
    {
        unset($this->tasks[$index]);
    }

    public function render()
    {
        return view('livewire.todo-list');
    }
}

Update the Blade view file to include a form for adding tasks and buttons for removing tasks.

<div>
    <h1>My To-Do List</h1>

    <form wire:submit.prevent="addTask">
        <input type="text" wire:model="newTask" placeholder="Add a new task">
        <button type="submit">Add Task</button>
    </form>

    <ul>
        @foreach($tasks as $index => $task)
            <li>
                {{ $task }}
                <button wire:click="removeTask({{ $index }})">Remove</button>
            </li>
        @endforeach
    </ul>
</div>

This example demonstrates how Laravel Livewire simplifies the creation of dynamic and interactive components.