Laravel 9 Dynamically Add or Remove Multiple Input Fields with jQuery

Laravel dynamic add/remove input fields and save to database example; In this step by step guide tutorial you will learn how to add or remove form multiple input fields dynamically in Laravel application with the help of jQuery javascript.

So, this tutorial, explain how to add/remove multiple input fields dynamically using jquery in the laravel app with validation error messages.

How to Dynamically Add or Remove Multiple Input Fields in Laravel

Follow the follosing step by steps instructions for how dynamically add/remove multiple input fields and submit to the database in laravel using jQuery.

  • Step 1: Download Laravel App
  • Step 2: Connect App to Database
  • Step 3: Build Model and Migration
  • Step 4: Add Routes
  • Step 5: Create and Configure Controller
  • Step 6: Create Blade View File
  • Step 7: Start and Test Laravel App

Download Laravel App

First at all create new laravel 9 application adding the following command in terminal.

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

Now Go into the app:

laravel-livewire

Connect App to Database

Open the .env file and add your database credentials such as database name, username equally important password:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=db name
DB_USERNAME=db user name
DB_PASSWORD=db password

Build Model and Migration

Next step, we need to execute the following command on terminal to generate model, migration file using the following command:

php artisan make:model OrderProduct -m

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

<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
class OrderProduct extends Model
{
    use HasFactory;
    public $fillable = ['name', 'quantity', 'price'];
}

Next, open database/migrations/create_order_products_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 CreateOrderProductsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('order_products', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->integer('quantity');
            $table->double('price', 8, 2)->default(0.00);
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('students');
    }
}

After that, run the following command to migrate the table into select database:

php artisan migrate

Add Routes

In this step, Navigate to the app/routes folder then open and update the following code in the routes/web.php file.

<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\OrderProductController;
/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
*/
Route::get('/order-products', [OrderProductController::class, 'index']);
Route::post('/order-products', [OrderProductController::class, 'store']);

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

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

<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Models\OrderProduct;
class OrderProductController extends Controller
{
    public function index() 
    {
        return view("order-products");
    }
    public function store(Request $request)
    {
        $request->validate([
            'products.*.subject' => 'required'
        ]);
     
        foreach ($request->products as $key => $product) {
            OrderProduct::create($product);
        }
     
        return back()->with('success', 'New order prodcuts has been added.');
    }
}

Create Blade View File

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/order-products.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 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>Name</th>
                    <th>Quantity</th>
                    <th>Price</th>
                    <th>Action</th>
                </tr>
                <tr>
                    <td>
                      <input type="text" name="addMoreInputFields[0][name]" placeholder="Enter Name" class="form-control" />
                    </td>
                    <td>
                      <input type="text" name="addMoreInputFields[0][quantity]" placeholder="Enter Quantity" class="form-control" />
                    </td>
                    <td>
                      <input type="text" name="addMoreInputFields[0][price]" placeholder="Enter Price" class="form-control" />
                    </td>
                    <td><button type="button" name="add" id="add-product" class="btn btn-outline-primary">Add Product</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;
    $("#add-product").click(function () {
        ++i;
        $("#dynamicAddRemove").append('<tr><td><input type="text" name="addmore['+i+'][name]" placeholder="Enter Name" class="form-control" /></td><td><input type="text" name="addmore['+i+'][quantity]" placeholder="Enter Quantity" class="form-control" /></td><td><input type="text" name="addmore['+i+'][price]" placeholder="Enter Price" class="form-control" /></td><td><button type="button" class="btn btn-danger remove-tr">Remove</button></td></tr>');
    });
    $(document).on('click', '.remove-input-field', function () {
        $(this).parents('tr').remove();
    });
</script>
</html>

Start and Test Laravel App

Finally, run the following command to start the development server for laravel – dynamically add/ remove multiple input fields using jquery app:

php artisan serve

Now, open browser and hit the following URLs into it:

http://localhost:8000/order-products

So this was it;  Laravel 9 dynamically add/remove multiple input fields and submit to database with jquery. In this tutorial, we have learned how to dynamically add or remove multiple input fields using jquery , javascript in laravel 9 app.