Laravel 9 Add/Remove Multiple Input Fields Dynamically with jQuery

As a developer, we work with form fields to get the values from the user to show or store the information.

But, wait, have you ever dealt with the situation where you have to give authority to the user to create multiple input fields dynamically.

If you are a laravel developer and want to integrate similar functionality in laravel.

In this comprehensive tutorial, we will tell you how to eloquently and dynamically add and remove multiple form input fields in Laravel using the notable JavaScript jQuery library.

After integrating dynamic input fields in laravel, you will easily add or remove multiple or more than one input field in the laravel app, which will utterly help your users share extra information.

To create dynamic input fields, we will use popular Bootstrap 5 CSS library; the Bootstrap 5 make our job facile in adding and removing input field element from design outlook.

How to Create Multiple Add/Remove Input Fields Feature in Laravel 9

  • Step 1: Download Laravel Project
  • Step 2: Connect to Database
  • Step 3: Setup Migration & Model
  • Step 4: Create Contact Controller
  • Step 5: Register New Routes
  • Step 6: Create Blade View
  • Step 7: View Application in Browser

Download Laravel Project

To add/remove multiple input fields dynamically with jQuery in laravel, start downloading a new app.

composer create-project --prefer-dist laravel/laravel laravel_star-trek

Connect to Database

Connect laravel application to the database by adding database details in .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db_name
DB_USERNAME=db_username
DB_PASSWORD=db_password

Setup Migration & Model

Next, run command to create new migration and model file.

php artisan make:model Contact -m

Add the table value which will store the dynamic input field’s values in database/migrations/create_contacts_table.php.

<?php

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

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

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

Likewise, add the table value into the app/Models/Contact.php file.

<?php

namespace App\Models;

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

class Contact extends Model
{
    use HasFactory;
    
    protected $fillable = [
        'hobbies'
    ];     
}

Without further ado, execute the command to invoke the migration, after which you may see the new table created in the database.

php artisan migrate

Create Contact Controller

Furthermore, you require a separate controller, where you can define the code to validate the multiple input values and store the values in the database.

php artisan make:controller ContactController

In this section, you will have to head over to app\Http\Controllers\ContactController.php file and place the provided code into the file.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\Contact;


class ContactController extends Controller
{
    public function index() 
    {
        return view("contact");
    }

    public function submitForm(Request $request)
    {
        $request->validate([
            'multiInput.*.subject' => 'required'
        ]);
     
        foreach ($request->multiInput as $key => $value) {
            Contact::create($value);
        }
     
        return back()->with('success', 'Form has been submitted.');
    }
}

Register New Routes

Controller logic doesn’t work unless it is connected to route, consequently create few new routes in routes/web.php file.

<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\ContactController;



Route::get('/contact', [ContactController::class, 'index']);
Route::post('/add-multi-values', [ContactController::class, 'submitForm']);

Create Blade View

In the last section, we will conjugate the whole code to define multiple input fields, get into the resources/views folder, create a new contact.blade.php file and then add the provided code in resources/views/contact.blade.php file.

<!DOCTYPE html>
<html>

<head>
    <meta charset="utf-8">
    <title>Laravel Multi Add and Remove Input Fields Example</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
</head>

<body>
    <div class="container mt-5">
        <form method="POST" action="{{ url('add-multi-values') }}">
            @csrf
            @if ($errors->any())
            <div class="alert alert-warning">
                <ul>
                    @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif
            @if (Session::has('success'))
            <div class="alert alert-info">
                <p>{{ Session::get('success') }}</p>
            </div>
            @endif
            <table class="table" id="multiForm">
                <tr>
                    <th>Add Hobbies</th>
                    <th>Remove</th>
                </tr>
                <tr>
                    <td><input type="text" name="multiInput[0][hobbies]" class="form-control"/></td>
                    <td><input type="button" name="add" value="Add" id="addRemoveIp" class="btn btn-outline-dark"></td>
                </tr>
            </table>

            <div class="d-grid mt-3">
              <input type="submit" class="btn btn-dark btn-block" value="Submit">
            </div>  
        </form>
    </div>
</body>


<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
    var i = 0;
    $("#addRemoveIp").click(function () {
        ++i;
        $("#multiForm").append('<tr><td><input type="text" name="multiInput['+i+'][hobbies]" class="form-control" /></td><td><button type="button" class="remove-item btn btn-danger">Delete</button></td></tr>');
    });
    $(document).on('click', '.remove-item', function () {
        $(this).parents('tr').remove();
    });
</script>
</html>

View App in Browser

So, far we have described everything eloquently, now; to commemorate the functionality, we will start the laravel project and view the app in the browser using the given url.

php artisan serve
http://127.0.0.1:8000/contact

Javascript add multiple input fields dynamically in laravel

Conclusion

Throughout this intense guide, we focused on explaining things with precision. We shared practical methods to persuade how to add multiple input fields in laravel eloquently.

We took the help of the jQuery library. Apart from that, we told you how to validate multiple input fields in laravel.

We created a simple form and displayed multi form input fields in rows with input fields. To design the dynamic add and remove input fields, we used the Bootstrap 5 library.