Laravel Livewire Add or Remove Dynamically Input Fields Example

In this tutorial, you will learn about Laravel livewire add or remove Dynamically input fields by using a simple example. You can use Laravel livewire with Laravel 6, Laravel 7, Laravel 8, and Laravel 9 versions.

Livewire is a full-stack framework for Laravel framework that is used to build simple dynamic interfaces. If you are using livewire with Laravel, then you don’t need to write the jQuery ajax code, livewire will provide a very simple way to write jQuery ajax code using PHP.

We will take a simple example of creating a contacts table with name and phone number and storing that data in the database without refreshing the page in a single form. Only the livewire/livewire package will be used.

So, let’s follow the below step:

Step 1: Install Laravel 8

Get the latest Laravel 8 version application by running the below command.

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

Step 2: Create Migration and Model

Create the database migration for the files table and model for the 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

Create a Contact model by using the 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

Install the livewire to laravel  application using below command:

composer require livewire/livewire

Step 4: Create Component

Create a livewire component using their command. Run the below command to create and add more components.

php artisan make:livewire contacts

Now, create files on both paths:

app/Http/Livewire/Contacts.php

resources/views/livewire/contacts.blade.php

Now, update both the files as below for 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') <span class="text-danger error">{{ $message }}</span>@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') <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="text" class="form-control" wire:model="phone.{{ $value }}" placeholder="Enter phone">
                            @error('phone.'.$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">Submit</button>
            </div>
        </div>
  
    </form>
</div>

Step 5: Create Route

Create one route for calling the above example. Add new route to web.php file as bellow:

routes/web.php

Route::get('contacts', function () {
    return view('default');
});

Step 6: Create View File

Create blade file for call form route. In this file, we will be using @livewireStyles, @livewireScripts, and @livewire(‘contact-form’).

resources/views/default.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Livewire Example </title>
    @livewireStyles
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous">
</head>
<body>
    
<div class="container">
    
    <div class="card">
      <div class="card-header">
        Laravel Livewire Example 
      </div>
      <div class="card-body">
        @livewire('contacts')
      </div>
    </div>
        
</div>
    
</body>
  
@livewireScripts
  
</html>

Now, run using the below command:

php artisan serve

The output will show Livewire Add or Remove Dynamically Input Fields

Laravel Livewire Add or Remove Dynamically Input Fields Example

Also read Laravel Livewire Change Event Example