Laravel Livewire Add or Remove Dynamically Input Fields Example

Laravel Livewire Add or Remove Dynamically Input Fields Example

Learn how to works Laravel livewire add more dynamically input fields. We will create simple add remove dynamic textbox example using Laravel livewire. You can use Laravel livewire with Laravel 6, Laravel 7 and Laravel 8 version.

Here, i will show you how to works laravel livewire add more dynamically input fields. i explained simply about laravel livewire add or remove dynamically input fields. This tutorial will give you simple example of laravel livewire add more input fields example. i would like to share with you add remove dynamic textbox laravel livewire.

In this tutorial, we will create simple add remove dynamic textbox example using laravel livewire. you can use laravel livewire with laravel 6, laravel 7 and laravel 8 version.

Livewire is a full-stack framework for Laravel framework that makes building dynamic interfaces simple, without leaving the comfort of Laravel. if you are using livewire with laravel then you don't worry about writing jquery ajax code, livewire will help to write very simple way jquery ajax code using php. without page refresh laravel validation will works, form will submit etc.

Here, i will give you very simple example to contacts table with name and phone number and i will store that data to database without refresh page in single form. we will use only livewire/livewire package.

So, let's follow bellow step and you will get bellow layout:

Step 1 : Install Laravel 8

first of all we need to get fresh Laravel 8 version application using bellow command, So open your terminal OR command prompt and run bellow command:

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

Step 2 : Create Migration and Model

Here, we need create database migration for files table and also we will create model for files table.

php artisan make:migration create_contacts_table

Migration:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

class CreateContactcTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('contacts', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('phone');
            $table->timestamps();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('contacts');
    }
}
php artisan migrate

now we will create Contact model by using following command:

php artisan make:model Contact

App/Models/Contact.php

<?php

namespace App\Models;

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

class Contact extends Model
{
    use HasFactory;

    protected $fillable = [
        'name', 'phone'
    ];
}

Step 3: Install Livewire

now in this step, we will simply install livewire to our laravel 8 application using bellow command:

composer require livewire/livewire

Step 4: Create Component

Now here we will create livewire component using their command. so run bellow command to create add more component.

php artisan make:livewire contacts

Now they created fies on both path:

app/Http/Livewire/Contacts.php

resources/views/livewire/contacts.blade.php

Now both file we will update as bellow for our contact us form.

app/Http/Livewire/Contacts.php

<?php

namespace App\Http\Livewire;

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

class Contacts extends Component
{
    public $contacts, $name, $phone, $contact_id;
    public $updateMode = false;
    public $inputs = [];
    public $i = 1;

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function add($i)
    {
        $i = $i + 1;
        $this->i = $i;
        array_push($this->inputs ,$i);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function remove($i)
    {
        unset($this->inputs[$i]);
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function render()
    {
        $this->contacts = Contact::all();
        return view('livewire.contacts');
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    private function resetInputFields(){
        $this->name = '';
        $this->phone = '';
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store()
    {
        $validatedDate = $this->validate([
                'name.0' => 'required',
                'phone.0' => 'required',
                'name.*' => 'required',
                'phone.*' => 'required',
            ],
            [
                'name.0.required' => 'name field is required',
                'phone.0.required' => 'phone field is required',
                'name.*.required' => 'name field is required',
                'phone.*.required' => 'phone field is required',
            ]
        );

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

        $this->inputs = [];

        $this->resetInputFields();

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

resources/views/livewire/file-upload.blade.php

<div>
    @if (session()->has('message'))
        <div class="alert alert-success">
          {{ session('message') }}
        </div>
    @endif

    <table class="table table-bordered">
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Phone</th>
        </tr>
        @foreach($contacts as $key => $value)
            <tr>
                <td>{{ $value->id }}</td>
                <td>{{ $value->name }}</td>
                <td>{{ $value->phone }}</td>
            </tr>
        @endforeach
    </table>

    <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')  {{ $message }}@enderror
                    </div>
                </div>
                <div class="col-md-5">
                    <div class="form-group">
                        <input type="phone" class="form-control" wire:model="phone.0" placeholder="Enter Phone">
                        @error('phone.0')  {{ $message }}@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)  {{ $message }}@enderror
                        </div>
                    </div>
                    <div class="col-md-5">
                        <div class="form-group">
                            <input type="text" class="form-control" wire:model="phone.{{ $value }}" placeholder="Enter phone">
                            @error('phone.'.$value)  {{ $message }}@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">Submit</button>
            </div>
        </div>

    </form>
</div>

laravel php web-development programming developer

Bootstrap 5 Complete Course with Examples

Bootstrap 5 Tutorial - Bootstrap 5 Crash Course for Beginners

Nest.JS Tutorial for Beginners

Hello Vue 3: A First Look at Vue 3 and the Composition API

Building a simple Applications with Vue 3

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

PHP Web Application Development Company

As a top **PHP Web Application Development Company in USA**[https://www.dataeximit.com/php-development-services/](https://www.dataeximit.com/php-development-services/ "https://www.dataeximit.com/php-development-services/"), we at Data EximIT have...

PHP Website Development

Skenix Infotech is a leading PHP Web Development Company that helps companies get results with industry best practices. Get affordable PHP Development Services.

Laravel Development Company

Skenix Infotech is a top Laravel Website Development Company with Expert Laravel Developers that provides robust Laravel Development Services at fair costs.

Hire Dedicated PHP Developer

Looking to hire affordable yet experienced PHP developers? **[Hire Dedicated PHP Developer](https://hourlydeveloper.io/hire-dedicated-php-developer/ "Hire Dedicated PHP Developer")**, who can convert your idea to reality, within the stipulated...

Hire PHP Developer

Looking to develop a PHP based website from scratch or revamp your existing website? **[HourlyDeveloper.io](https://hourlydeveloper.io/ "HourlyDeveloper.io")** has always been an industry leader for companies and business owners looking to hire...