How to Add and Remove Rows in Laravel 10 Livewire

Hello developers! Today, I'm excited to share with you a step-by-step guide on how to add and remove rows in Laravel 10 using Livewire seamlessly. Livewire has become a game-changer in simplifying the integration of real-time features into Laravel applications, and managing dynamic rows is no exception.

In this article, we'll learn about how to add and remove rows in laravel 10 Livewire. You can dynamically add rows and delete rows in Laravel 8, Laravel 9, and Laravel 10 using livewire.

So, let's dive in and explore how to enhance your Laravel project with the power of Livewire in laravel 10 livewire adds and deletes rows.

Step 1: Install Laravel 10 Application

You can create a new Laravel project using the following command:

composer create-project --prefer-dist laravel/laravel my-laravel-project

 

Step 2: Set Up Laravel 10 with Livewire

Before we get into the nitty-gritty of adding and removing rows, make sure you have a Laravel 10 project up and running. If you haven't installed Livewire yet, you can do so by running the following command:

composer require livewire/livewire

 

Step 3: Configure a Database

Open the .env file in your Laravel project directory:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

 

Step 4: Create a Model and Migration

Now, we'll create a model and migration using the following command:

php artisan make:model Employee -m 

Open the model file in the app directory (e.g., app/Models/Employee.php)

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Employee extends Model
{
    use HasFactory;
    protected $guarded = [];
}

Migration:

public function up()
{
    Schema::create('employees', function (Blueprint $table) {
        $table->bigIncrements('id');
        $table->string('name');
        $table->string('email');
        $table->timestamps();
    });
}

Execute the following command to run the migration and create the database table:

php artisan migrate

 

Step 5: Create a Livewire Component

Now, let's create a Livewire component to handle our dynamic rows. Run the following command to generate a new Livewire component:

php artisan make:livewire employees

This will create a new Livewire component in the app/Http/Livewire directory.

app/Http/Livewire/Employees.php
resources/views/livewire/employees.blade.php

app/Http/Livewire/Employees.php

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\Models\Employee;
use App\Http\Livewire\Field;
use Illuminate\Http\Request;

class Employees extends Component
{
    public $employees, $name, $email, $employee_id;
    public $updateMode = false;
    public $inputs = [];
    public $i = 1;

    public function add($i)
    {
        $i = $i + 1;
        $this->i = $i;
        array_push($this->inputs ,$i);
    }

    public function remove($i)
    {
        unset($this->inputs[$i]);
    }

    public function render()
    {
        $this->employees = Employee::all();
        return view('livewire.employees');
    }

    private function resetInputFields(){
        $this->name = '';
        $this->email = '';
    }

    public function store()
    {
        $validatedDate = $this->validate([
                'name.0' => 'required',
                'email.0' => 'required',
                'name.*' => 'required',
                'email.*' => 'required|email',
            ],
            [
                'name.0.required' => 'name field is required',
                'email.0.required' => 'email field is required',
	            'email.0.email' => 'The email must be a valid email address.',
                'name.*.required' => 'name field is required',
                'email.*.required' => 'email field is required',
                'email.*.email' => 'The email must be a valid email address.',
            ]
        );

        foreach ($this->name as $key => $value) {
            Employee::create(['name' => $this->name[$key], 'email' => $this->email[$key]]);
        }

        $this->inputs = [];

        $this->resetInputFields();

        session()->flash('message', 'Employee Has Been Created Successfully.');
    }
}

resources/views/livewire/employees.blade.php

<div>
    @if (session()->has('message'))
        <div class="alert alert-success">
          {{ session('message') }}
        </div>
    @endif
    <form>
        <div class=" add-input">
            <div class="row">
                <div class="col-md-5">
                    <div class="form-group">
                        <input type="text" class="form-control" placeholder="Enter Name" wire:model="name.0">
                        @error('name.0') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                </div>
                <div class="col-md-5">
                    <div class="form-group">
                        <input type="email" class="form-control" wire:model="email.0" placeholder="Enter Email">
                        @error('email.0') <span class="text-danger error">{{ $message }}</span>@enderror
                    </div>
                </div>
                <div class="col-md-2">
                    <button class="btn text-white btn-info btn-sm" wire:click.prevent="add({{$i}})">Add</button>
                </div>
            </div>
        </div>

        @foreach($inputs as $key => $value)
            <div class=" add-input">
                <div class="row">
                    <div class="col-md-5">
                        <div class="form-group">
                            <input type="text" class="form-control" placeholder="Enter Name" wire:model="name.{{ $value }}">
                            @error('name.'.$value) <span class="text-danger error">{{ $message }}</span>@enderror
                        </div>
                    </div>
                    <div class="col-md-5">
                        <div class="form-group">
                            <input type="email" class="form-control" wire:model="email.{{ $value }}" placeholder="Enter Email">
                            @error('email.'.$value) <span class="text-danger error">{{ $message }}</span>@enderror
                        </div>
                    </div>
                    <div class="col-md-2">
                        <button class="btn btn-danger btn-sm" wire:click.prevent="remove({{$key}})">remove</button>
                    </div>
                </div>
            </div>
        @endforeach
        <div class="row">
            <div class="col-md-12">
                <button type="button" wire:click.prevent="store()" class="btn btn-success btn-sm">Save</button>
            </div>
        </div>
    </form>
</div>
// techsolutionstuff.com

 

Step 6: Add Route

Then, open routes/web.php the file. define a route in this file.

Route::get('/employees', function () {
    return view('home');
});

 

Step 7: Create the Blade View

Now, open the home.blade.php file. Add the below code to that file.

resources/views/home.blade.php

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">

        <title>How to Add and Remove Rows in Laravel 10 Livewire - Techsolutionstuff</title>

        <!-- Fonts -->
        <link href="https://fonts.googleapis.com/css?family=Nunito:200,600" rel="stylesheet">

        <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.1/css/bootstrap.min.css">

        <!-- Styles -->
        <style>
            html, body {
                background-color: #fff;
                color: #636b6f;
                font-family: 'Nunito', sans-serif;
                font-weight: 200;
                height: 100vh;
                margin: 0;
            }

            .full-height {
                height: 100vh;
            }

            .flex-center {
                align-items: center;
                display: flex;
                justify-content: center;
            }

            .position-ref {
                position: relative;
            }

            .top-right {
                position: absolute;
                right: 10px;
                top: 18px;
            }

            .content {
                text-align: center;
            }

            .title {
                font-size: 84px;
            }

            .links > a {
                color: #636b6f;
                padding: 0 25px;
                font-size: 13px;
                font-weight: 600;
                letter-spacing: .1rem;
                text-decoration: none;
                text-transform: uppercase;
            }

            .m-b-md {
                margin-bottom: 30px;
            }
        </style>
    </head>
<body>
    <div class="container mt-5">
        <div class="row mt-5 justify-content-center">
            <div class="mt-5 col-md-8">
                <div class="card">
                    <div class="card-header bg-success text-white"><h5 style="font-size: 19px;">How to Add and Remove Rows in Laravel 10 Livewire - Techsolutionstuff</h5></div>

                    <div class="card-body">
                        @livewire('employees')
                    </div>
                </div>
            </div>
        </div>
    </div>
    @livewireScripts
</body>
// techsolutionstuff.com
</html>

 

Step 8: Run Laravel 10 Application

Run the following command to start the server:

php artisan serve

 

Conclusion:

In conclusion, diving into the world of Laravel 10 with Livewire has been an enlightening journey. We've explored the laravel 10 livewire add and remove rows. You can easily add and delete rows with the help of livewire in laravel 10.

 


You might also like:

techsolutionstuff

Techsolutionstuff | The Complete Guide

I'm a software engineer and the founder of techsolutionstuff.com. Hailing from India, I craft articles, tutorials, tricks, and tips to aid developers. Explore Laravel, PHP, MySQL, jQuery, Bootstrap, Node.js, Vue.js, and AngularJS in our tech stack.

RECOMMENDED POSTS

FEATURE POSTS