Dynamically Add or Remove Multiple Input Fields Using Jquery Laravel 10

Apr 10, 2024 | Laravel 10 jQuery Bootstrap Laravel Laravel


Hello Dev,

Today, I'll guide you through the process of dynamically adding and removing input fields using jQuery and submitting them to the database in a Laravel 10 application. Adding more input fields dynamically in Laravel 10 is straightforward. We'll create functionality to add and remove groups of input fields dynamically using jQuery within a Laravel environment.

We'll implement dynamic form fields, allowing users to add and remove input rows with Bootstrap 5 and jQuery in Laravel. Additionally, we'll utilize Laravel's validation feature to validate the dynamically added input fields.

Often, there's a need to input the same information multiple times using the same form input. Therefore, we'll create table rows with input fields and an "Add More" button. Clicking this button will append a new row with input fields dynamically.

Let's proceed with implementing this functionality in our Laravel 10 application.

Step 1: Install Laravel 10

This step is optional; however, if you haven't already created the Laravel application, you can proceed by executing the following command:

composer create-project laravel/laravel blog
Step 2: Database Configuration

In the second step, we'll configure the database settings such as the database name, username, password, etc. for our Laravel 10 CRUD application. To do this, let's open the .env file and input the details as shown below:

.env
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=here your database name(blog)
DB_USERNAME=here database username(root)
DB_PASSWORD=here database password(root)
Step 3: Create stocks Table

To create a migration for the "stock" table using Laravel's Artisan command-line tool, you can follow these steps:

Open your terminal or command prompt.

Navigate to your Laravel project directory.

Run the following command to generate a new migration file for the "stock" table:

php artisan make:migration create_stock_table

This command will create a new migration file in the database/migrations directory of your Laravel project.

Open the generated migration file. You can find it in the database/migrations directory.

Add the code to define the schema for the "stock" table within the up method of the migration file. Here's an example of what the migration file might look like:

database/migrations
<?php

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

class CreateStockTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('stock', function (Blueprint $table) {
            $table->id();
            $table->string('product_name');
            $table->integer('quantity');
            $table->integer('price');
            $table->timestamps();
        });
    }

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

After defining the schema in the migration file, run the migration command to create the "stock" table in your database:

php artisan migrate

This command will execute the migration and create the "stock" table in your database according to the schema defined in the migration file.

Now, you have successfully created the "stock" table using Laravel's migration feature. You can proceed to use this table in your application to manage stock-related data.

Step 4: Create stocks Model

To create a model for the "stock" table in Laravel, you can follow these steps:

Open your terminal or command prompt.

Navigate to your Laravel project directory.

Run the following Artisan command to generate a new model for the "stock" table:

php artisan make:model Stock

This command will create a new model file named Stock.php in the app directory of your Laravel project.

Open the generated Stock.php file located in the app directory.

Inside the Stock model class, you can define the table name and any other model-specific properties or relationships. Here's an example of what the Stock model might look like:

app/Stock.php
<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Stock extends Model
{
    // Define the table name explicitly
    protected $table = 'stock';

    // Define fillable attributes
    protected $fillable = [
        'product_name',
        'quantity',
        'price',
    ];
}

To add routes for handling the "add more fields" functionality, you can modify your routes/web.php file as follows:

Step 5: Add Routes routes/web.php
<?php

use Illuminate\Support\Facades\Route;

// Define route for showing the form
Route::get('add-more-fields', 'DynamicFieldsController@addMoreFields')->name('add.more.fields');

// Define route for submitting the form
Route::post('submit-fields', 'DynamicFieldsController@submitFields')->name('submit.fields');
Step 6: Create StockController

These routes define the endpoints for showing the form (add-more-fields) and submitting the form (submit-fields). Adjust the route URIs and controller methods according to your application's requirements.

Now, you can proceed to implement the controller methods for handling these routes in your DynamicFieldsController.

To create a new controller named StockController in Laravel, you can use the following Artisan command:

php artisan make:controller StockController --resource

This command will generate a new controller file named StockController.php in the app/Http/Controllers directory of your Laravel project.

After creating the controller, you can define the required methods for your functionality.

After bellow command you will find new file in this path

app/Http/Controllers/StockController.php.
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Stock;

class StockController extends Controller
{
    /**
     * Show the form for adding more fields.
     *
     * @return \Illuminate\Http\Response
     */
    public function addMore()
    {
        return view('add_more_fields');
    }

    /**
     * Add more stock fields.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function addMoreStock(Request $request)
    {
        $rules = [
            'product_name.*' => 'required',
            'quantity.*' => 'required|numeric',
            'price.*' => 'required|numeric',
        ];

        $messages = [
            'product_name.*.required' => 'Product name is required',
            'quantity.*.required' => 'Quantity is required',
            'quantity.*.numeric' => 'Quantity must be numeric',
            'price.*.required' => 'Price is required',
            'price.*.numeric' => 'Price must be numeric',
        ];

        $this->validate($request, $rules, $messages);

        foreach ($request->product_name as $key => $value) {
            Stock::create([
                'product_name' => $request->product_name[$key],
                'quantity' => $request->quantity[$key],
                'price' => $request->price[$key],
            ]);
        }

        return back()->with('success', 'Stock added successfully.');
    }
}

In this example:

The addMore() method is responsible for displaying the form for adding more fields.

The addMoreStock() method handles the submission of the form data for adding more stock fields. It validates the input fields and then creates new stock records using the Stock model.

Ensure that you adjust the method names and validation rules/messages according to your application's requirements.

With this StockController in place, you can now handle adding more stock fields in your Laravel application.

Step 7: Create Blade File resources/views/addMoreFields.blade.php

You can change the latest bootstrap script and js according to you
<!DOCTYPE html>
<html>
<head>
    <title>Dynamically Add or Remove Multiple Input Fields Using Jquery Laravel 10 -- ITErrorSolution.com</title>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">
    <script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>
</head>
<body>
   
<div class="container">
    <h2 align="center">Dynamically Add or Remove Multiple Input Fields Using Jquery Laravel 10 -- ITErrorSolution.com</h2> 
   
    <form action="{{ route('addmorePost') }}" method="POST">
        @csrf
   
        @if ($errors->any())
            <div class="alert alert-danger">
                <ul>
                    @foreach ($errors->all() as $error)
                        <li>{{ $error }}</li>
                    @endforeach
                </ul>
            </div>
        @endif
   
        @if (Session::has('success'))
            <div class="alert alert-success text-center">
                <a href="#" class="close" data-dismiss="alert" aria-label="close">×</a>
                <p>{{ Session::get('success') }}</p>
            </div>
        @endif
   
        <table class="table table-bordered" id="dynamicTable">  
            <tr>
                <th>Product Name</th>
                <th>Quantity</th>
                <th>Price</th>
                <th>Action</th>
            </tr>
            <tr>  
                <td><input type="text" name="addmore[0][product_name]" placeholder="Enter Product Name" class="form-control" /></td>  
                <td><input type="text" name="addmore[0][quantity]" placeholder="Enter Quantity" class="form-control" /></td>  
                <td><input type="text" name="addmore[0][price]" placeholder="Enter Price" class="form-control" /></td>  
                <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>  
            </tr>  
        </table> 
    
        <button type="submit" class="btn btn-success">Save</button>
    </form>
</div>
   
<script type="text/javascript">
   
    var i = 0;
       
    $("#add").click(function(){
   
        ++i;
   
        $("#dynamicTable").append('<tr><td><input type="text" name="addmore['+i+'][product_name]" placeholder="Enter Product 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-tr', function(){  
         $(this).parents('tr').remove();
    });  
   
</script>
  
</body>
</html>
Run Laravel App:

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

http://localhost:8000/users

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#Laravel 10
#jQuery
#Bootstrap
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"