Laravel 8 Dynamically Add or Remove Multiple Input Fields with jQuery

Last updated on by Digamber

This is a Laravel 8 dynamic add/remove input fields comprehensive tutorial; in this extensive guide, we will explain how to profoundly add or remove form input fields in Laravel application with the help of jQuery.

Users interact with web application and mobile application through web forms, especially to get done some specific work. We create forms fields with static input elements to get user information; nevertheless, seldom, pre-defined input fields are not enough.

With the help of this tutorial, we will step by step explain how to add/remove multiple input fields dynamically using jquery in the laravel 8 app.

How to Dynamically Add or Remote Multiple Input Fields in Laravel 8

Here are the complete set of instructions that will help you learn how dynamically add/remove multiple input fields and submit to the database in laravel using jQuery.

  • Step 1: Create Laravel 8 Project
  • Step 2: Add Database Details in ENV
  • Step 3: Set Up Model and Migration
  • Step 4: Generate and Configure Controller
  • Step 5: Create Routes
  • Step 6: Prepare Blade View
  • Step 7: Start and Test Laravel Application

Create Laravel 8 Project

Composer is the foundational tool that allows you to develop a laravel application and make sure you have installed a composer on your system.

After which, head over to the terminal, type the command on the command prompt and execute the following command to install the new laravel application.

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

Thereafter, get inside the app directory:

cd laravel_demo_app

Add Database Details in ENV

In order to store the input field values to the database, you have to connect the laravel app to the database. This can be done by adding the database name, username, and password inside the .env file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_user_name
DB_PASSWORD=database_password

Set Up Model and Migration

This step tells how to create model and migration files, store dynamic input fields value into the database, and, consequently, run command to create Student migration files.

php artisan make:model Student -m

In this step, you have to register the subject property inside the fillable array within the app/Models/Student.php file.

<?php

namespace App\Models;

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

class Student extends Model
{
    use HasFactory;
    protected $fillable = [
        'subject'
    ];    
}

In the next instruction, you will understand how to register new property in the migration file, open database/migrations/create_students_table.php file and update the new value inside the up() method.

<?php

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

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

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

We are all set to migrate the new table into the database, just execute the command and make sure to check your database after that.

php artisan migrate

Generate and Configure Controller

This step consists of generating a new laravel controller and making the controller ready with PHP logic to create dynamic form fields using jQuery.

php artisan make:controller StudentController

After executing above command a new controller file manifested, now you need to add the following code in app\Http\Controllers\StudentController.php this file and then save the file.

<?php

namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\Student;

class StudentController extends Controller
{
    public function index() 
    {
        return view("welcome");
    }

    public function store(Request $request)
    {
        $request->validate([
            'addMoreInputFields.*.subject' => 'required'
        ]);
     
        foreach ($request->addMoreInputFields as $key => $value) {
            Student::create($value);
        }
     
        return back()->with('success', 'New subject has been added.');
    }
}

Create Routes

Add student controller, then create GET and POST methods using the controller to show student form and add and remove input fields. You have to open and update the following code in the routes/web.php file.

<?php

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

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/

Route::get('/student-form', [StudentController::class, 'index']);
Route::post('/store-input-fields', [StudentController::class, 'store']);

Prepare Blade View

In this last step, we need to create the basic form; we will use Bootstrap 5 and jQuery to create the form that allows the creation of multiple input fields dynamically.

Hence, open resources/views/welcome.blade.php file, and add the following code within the 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 8 Add/Remove Multiple Input Fields Example</title>
    <!-- CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet">
    <style>
      .container {
            max-width: 600px;
        }
    </style>
</head>

<body>
    <div class="container">
        <form action="{{ url('store-input-fields') }}" method="POST">
            @csrf
            @if ($errors->any())
            <div class="alert alert-danger" role="alert">
                <ul>
                    @foreach ($errors->all() as $error)
                    <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
            @endif
            @if (Session::has('success'))
            <div class="alert alert-success text-center">
                <p>{{ Session::get('success') }}</p>
            </div>
            @endif
            <table class="table table-bordered" id="dynamicAddRemove">
                <tr>
                    <th>Subject</th>
                    <th>Action</th>
                </tr>
                <tr>
                    <td><input type="text" name="addMoreInputFields[0][subject]" placeholder="Enter subject" class="form-control" />
                    </td>
                    <td><button type="button" name="add" id="dynamic-ar" class="btn btn-outline-primary">Add Subject</button></td>
                </tr>
            </table>
            <button type="submit" class="btn btn-outline-success btn-block">Save</button>
        </form>
    </div>
</body>

<!-- JavaScript -->
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/js/bootstrap.bundle.min.js"></script>
<script type="text/javascript">
    var i = 0;
    $("#dynamic-ar").click(function () {
        ++i;
        $("#dynamicAddRemove").append('<tr><td><input type="text" name="addMoreInputFields[' + i +
            '][subject]" placeholder="Enter subject" class="form-control" /></td><td><button type="button" class="btn btn-outline-danger remove-input-field">Delete</button></td></tr>'
            );
    });
    $(document).on('click', '.remove-input-field', function () {
        $(this).parents('tr').remove();
    });
</script>
</html>

Start and Test Laravel Application

First, you require to start the laravel development server to add or remove multiple input fields dynamically. Open terminal type given below command and execute the command.

php artisan serve

Once the development server is evoked, then you can use the following url to access the app.

http://127.0.0.1:8000/student-form

Laravel 8 Dynamic Add or Remove Input Fields

Conclusion

So this was it; we have eventually completed this tutorial and tried to comprehend through bit-by-bit instructions that how to dynamically add/remove multiple input fields and submit to database using jQuery in Laravel 8. We reckon this guide help surely clear the concept. If this tutorial was helpful, then make sure to share it with others.