Laravel 11 Add or Remove Multiple Input Fields with jQuery Example

By Hardik Savani September 4, 2024 Category : Laravel

Today, I will show you how to create add or remove multiple input fields and store into database in laravel 11 application. we will create dynamic add more input fields functionality with laravel 11 application.

In this example, we will create "products" and "product_stock" table. Then we will create form with product name and add more inputs for quantity and price, that way user can add multiple stock during product create. we also display products with sum of quantity. so let's see the below example step by step:

Step for Laravel 11 Add More Input Fields Dynamically Example

  • Step 1: Install Laravel 11
  • Step 2: Create Table Migration and Model
  • Step 3: Create Routes
  • Step 4: Create Controller
  • Step 5: Create Blade Files
  • Run Laravel App

Step 1: Install Laravel 11

First of all, we need to get a fresh Laravel 11 version application using the command below because we are starting from scratch. So, open your terminal or command prompt and run the command below:

composer create-project laravel/laravel example-app

Step 2: Create Table Migration and Model

In this step, we need to create products and product_stock table, models as well.

Create Migration

php artisan make:migration create_products_table

Migration

<?php

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

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

        Schema::create('product_stocks', function (Blueprint $table) {
            $table->id();
            $table->bigInteger("product_id");
            $table->integer("quantity");
            $table->integer("price");
            $table->timestamps();
        });
    }

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

Run migration now:

php artisan migrate

Create Model

run bellow command to create Product and ProductStock model:

php artisan make:model Product

php artisan make:model ProductStock

app/Models/Product.php

<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $fillable = ['name'];

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function stocks(): HasMany
    {
        return $this->hasMany(ProductStock::class);
    }
}

app/Models/ProductStock.php

<?php

namespace App\Models;

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

class ProductStock extends Model
{
    use HasFactory;

    protected $fillable = ['product_id', 'quantity', 'price'];
}

Step 3: Create Routes

In this is step we need to create some routes for add to cart function.

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\ProductController;

Route::get('/', function () {
    return view('welcome');
});

Route::get('add-more', [ProductController::class, 'index']);
Route::post('add-more', [ProductController::class, 'store'])->name('add-more.store');;

Step 4: Create Controller

in this step, we need to create ProductController and add following code on that file:

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

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

class ProductController extends Controller
{
    /**
     * Write code on Method
     *
     * @return response()
     */
    public function index()
    {
        $products = Product::paginate(10);
        return view('addMore', compact('products'));
    }

    /**
     * Write code on Method
     *
     * @return response()
     */
    public function store(Request $request)
    {
        $rules = [ "name" => "required", "stocks.*" => "required" ];

        foreach($request->stocks as $key => $value) {
            $rules["stocks.{$key}.quantity"] = 'required';
            $rules["stocks.{$key}.price"] = 'required';
        }

        $request->validate($rules);

        $product = Product::create(["name" => $request->name]);
        foreach($request->stocks as $key => $value) {
            $product->stocks()->create($value);
        }

        return redirect()->back()->with(['success' => 'Product created successfully.']);
    }
}

Step 5: Create Blade Files

here, we will create addMore.blade.php file with the following code.

resources/views/addMore.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 11 Add More Fields Example - ItSolutionStuff.com</title>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/5.0.1/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" />
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
      
<div class="container">
    <div class="card mt-5">
        <h3 class="card-header p-3">Laravel 11 Add More Fields Example - ItSolutionStuff.com</h3>
        <div class="card-body">

            @session('success')
                <div class="alert alert-success" role="alert"> 
                    {{ $value }}
                </div>
            @endsession

            <form method="post" action="{{ route('add-more.store') }}" enctype="multipart/form-data">
                @csrf
                <h5>Create Product:</h5>
                <div class="form-group">
                    <label>Name:</label>
                    <input type="text" name="name" class="form-control" placeholder="Enter Name" value="{{ request()->old('name') }}" />
                    @error('name')
                        <p class="text-danger">{{ $message }}</p>
                    @enderror
                </div>

                <table class="table table-bordered mt-2 table-add-more">
                    <thead>
                        <tr>
                            <th colspan="2">Add Stocks</th>
                            <th><button class="btn btn-primary btn-sm btn-add-more"><i class="fa fa-plus"></i> Add More</button></th>
                        </tr>
                    </thead>
                    <tbody>
                        @php
                            $key = 0;
                        @endphp
                        @if(request()->old('stocks'))
                            @foreach(request()->old('stocks') as $key => $stock)
                            <tr>
                                <td>
                                    <input type="number" name="stocks[{{$key}}][quantity]" class="form-control" placeholder="Quantity" value="{{ $stock['quantity'] ?? '' }}" />
                                    @error("stocks.{$key}.quantity")
                                        <p class="text-danger">{{ $message }}</p>
                                    @enderror
                                </td>
                                <td>
                                    <input type="number" name="stocks[{{$key}}][price]" class="form-control" placeholder="Price" value="{{ $stock['price'] ?? '' }}" />
                                    @error("stocks.{$key}.price")
                                        <p class="text-danger">{{ $message }}</p>
                                    @enderror
                                </td>
                                <td><button class="btn btn-danger btn-sm btn-add-more-rm"><i class="fa fa-trash"></i></button></td>
                            </tr>
                            @endforeach
                        @else
                            <tr>
                                <td><input type="number" name="stocks[0][quantity]" class="form-control" placeholder="Quantity" /></td>
                                <td><input type="number" name="stocks[0][price]" class="form-control" placeholder="Price" /></td>
                                <td><button class="btn btn-danger btn-sm btn-add-more-rm"><i class="fa fa-trash"></i></button></td>
                            </tr>
                        @endif
                    </tbody>
                </table>

                <div class="form-group mt-2">
                    <button type="submit" class="btn btn-success btn-block"><i class="fa fa-save"></i> Submit</button>
                </div>
            </form>

            <h5 class="mt-5">Product List:</h5>
            <table class="table table-bordered data-table">
                <thead>
                    <tr>
                        <th>ID</th>
                        <th>Name</th>
                        <th>Total Quantity</th>
                    </tr>
                </thead>
                <tbody>
                    @forelse($products as $product)
                        <tr>
                            <td>{{ $product->id }}</td>
                            <td>{{ $product->name }}</td>
                            <td>{{ $product->stocks->sum('quantity') }}</td>
                        </tr>
                    @empty
                        <tr>
                            <td colspan="3">There are no products.</td>
                        </tr>
                    @endforelse
                </tbody>
            </table>
          
            {!! $products->links('pagination::bootstrap-5') !!}
        </div>
    </div>
</div>
</body>

<script type="text/javascript">
    $(document).ready(function(){  

        i = "{{$key}}";
        
        $(".btn-add-more").click(function(e){
            e.preventDefault();
            i++;
            $(".table-add-more tbody").append('<tr><td><input type="number" name="stocks['+i+'][quantity]" class="form-control" placeholder="Quantity" /></td><td><input type="number" name="stocks['+i+'][price]" class="form-control" placeholder="Price" /></td><td><button class="btn btn-danger btn-sm btn-add-more-rm"><i class="fa fa-trash"></i></button></td></tr>');
        });

        $(document).on('click', '.btn-add-more-rm', function(){  
            $(this).parents("tr").remove();
        }); 

    });
</script> 
</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL, and view the app output:

http://localhost:8000/add-more

Output:

i hope it can help you...

Shares