Saturday, November 16, 2024
Google search engine
HomeLanguagesLaravel 8 Livewire – Dynamically Add or Remove input fields

Laravel 8 Livewire – Dynamically Add or Remove input fields

Laravel 8 livewire dynamically add or remove multiple input fields example tutorial from scratch. In this tutorial, we will show you how to implement add or remove multiple input fields dynamically using livewire in laravel.

Sometimes you need to add or remove multiple input fields with livewire forms in laravel 8 apps. So, this laravel livewire dynamically add/remove input fields tutorial will guide you step by step on how to add remove multiple input fields in laravel 8 app using livewire package. And save into the database.

Laravel 8 Livewire – Dynamically Add or Remove input fields

  • Step 1: Install Laravel 8 App
  • Step 2: Connecting App to Database
  • Step 3: Create Model & Migration using Artisan
  • Step 4: Install Livewire Package
  • Step 5: Build Livewire Component using Artisan
  • Step 6: Create Route
  • Step 7: Create View File
  • Step 8: Run Development Server

Step 1: Install Laravel 8 App

First of all, Open your terminal OR command prompt and execute following command to install laravel fresh app for laravel livewire add or remove multiple input fields dynamically project:

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

Step 2: Connecting App to Database

In this step, Add database credentials in the .env file. So open your project root directory and find .env file. Then add database detail in .env file:

DB_CONNECTION=mysql  
DB_HOST=127.0.0.1  
DB_PORT=3306  
DB_DATABASE=here your database name here 
DB_USERNAME=here database username here 
DB_PASSWORD=here database password here

Step 3: Run Migration

In this step,execute the following command on terminal to generate model, migration file using the following command:

 php artisan make:model Employee -m 

This command will create one model name Employee.php, and create one migration that name create_employees_table.php

So, Navigate to database/migrations folder and open create_ employees_table.php file. Then update the following code into create_ employees_table.php file:

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

Next, open command prompt and execute the following command to create the table into your database:

php artisan migrate

Next, Navigate to app/Models/ directory and open Employee.php file. Then update the following code into it:

<?php

namespace App\Models;

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

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

Step 4: Install Livewire Package

In this step, you need to install livewire package to your laravel project using the following command:

composer require livewire/livewire

Step 5: Build Livewire Component using Artisan

In this step, create the livewire components for creating a livewire add or remove field component using the following command in laravel. So Open your cmd and execute the following command:

php artisan make:livewire employees

This command will create the following components on the following path:

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

Now, Navigate to app/Http/Livewire folder and open Employees.php file. Then add the following code into your Employees.php file:

<?php

namespace App\Http\Livewire;

use Livewire\Component;
use App\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.');
    }
}

After that, Navigate to resources/views/livewire folder and open employees.blade.php file. Then add the following code into your employees.blade.php file:

<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>

Step 6: Create Route

In this step, Navigate to routes folder and open web.php. Then add the following routes into your web.php file:

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

Step 7: Create View File

In this step, navigate to resources/views/ folder and create one blade view files that name home.blade.php file. Then add the following code into your home.blade.php file:

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

        <title>Laravel Livewire 8 Dynamically Add/Remove Input Fields - Tutsmake.com</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;">Laravel Livewire 8 Dynamically Add/Remove Input Fields - Tutsmake.com</h5></div>

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

Note that, if you want to add HTML(blade views), CSS, and script code into your livewire files. So, you can use @livewireStyles, @livewireScripts, and @livewire(‘ blade views’).

Step 8: Run Development Server

Finally, you need to execute the following PHP artisan serve command to start your laravel livewire add or remove input fields dynamically example app:

php artisan serve

If you want to run the project diffrent port so use this below command

php artisan serve --port=8080

Now, open browser and test laravel 8 livewire dynamically add or remove input fields app:

http://localhost:8000/employees

Recommended Laravel Posts

Dominic Rubhabha-Wardslaus
Dominic Rubhabha-Wardslaushttp://wardslaus.com
infosec,malicious & dos attacks generator, boot rom exploit philanthropist , wild hacker , game developer,
RELATED ARTICLES

Most Popular

Recent Comments