Laravel - Dynamically Add or Remove Input Fields Example

May 10, 2020 | Category : Laravel

I am going to explain you example of dynamically add input fields and submit to database with laravel. I’m going to show you about add/remove multiple input fields dynamically with jquery. i explained simply about laravel add more fields validation. you can understand a concept of laravel add more fields. Alright, let’s dive into the steps.

we will create dynamic form fields - add & remove with bootstrap 4 and jquery in laravel. you can also use laravel validation for add more input fields.

Add more multiple input fields like sometimes we need to add same information add multiple time with same form input. so we will create table row with input fields and add add more button so when you click on that button then it will append new row with input fields.

Preview:

Step 1 : Install Laravel

I am going to show you scratch, So we require to get fresh current Laravel 5.8 version application using bellow command, So open your terminal OR command prompt and run bellow command:

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

Step 2: Database Configuration

In this step we have to make database configuration for example database name, username, password etc for our application of laravel 5.8. So let's open .env file and fill all details like as bellow:

.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 product_stocks Table and Model

we are going to create add more dynamic field application for product_stocks. so we have to create migration for product_stocks table using Laravel 5.8 php artisan command, so first fire bellow command:

php artisan make:migration create_product_stocks_table

After this command you will find one file in following path database/migrations and you have to put bellow code in your migration file for create articles table.

<?php

use Illuminate\Support\Facades\Schema;

use Illuminate\Database\Schema\Blueprint;

use Illuminate\Database\Migrations\Migration;

class CreateProductStocksTable extends Migration

{

/**

* Run the migrations.

*

* @return void

*/

public function up()

{

Schema::create('product_stocks', function (Blueprint $table) {

$table->bigIncrements('id');

$table->string('name');

$table->integer('qty');

$table->integer('price');

$table->timestamps();

});

}

/**

* Reverse the migrations.

*

* @return void

*/

public function down()

{

Schema::dropIfExists('product_stocks');

}

}

Now run migration my following command:

php artisan migrate

After creating table we have to create model for "product_stocks" table so just run bellow command and create new model:

php artisan make:model ProductStock

Ok, so after run bellow command you will find app/ProductStock.php and put bellow content in ProductStock.php file:

app/ProductStock.php

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class ProductStock extends Model

{

public $table = "product_stocks";

public $fillable = ['name', 'qty', 'price'];

}

Step 4: Add Routes

In this is step we need to add two route for add more fields example. so open your routes/web.php file and add following route.

routes/web.php

Route::get("addmore","ProductAddMoreController@addMore");

Route::post("addmore","ProductAddMoreController@addMorePost")->name('addmorePost');

Step 5: Create ProductAddMoreController

Here, now we should create new controller as ProductAddMoreController if you haven't created. So run bellow command and create new controller. bellow controller for create resource controller.

php artisan make:controller ProductAddMoreController

After bellow command you will find new file in this path app/Http/Controllers/ProductAddMoreController.php.

In this controller will create seven methods by default as bellow methods:

1)addMore()

2)addMorePost()

So, let's copy bellow code and put on ProductAddMoreController.php file.

app/Http/Controllers/ProductAddMoreController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use App\ProductStock;

class ProductAddMoreController extends Controller

{

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function addMore()

{

return view("addMore");

}

/**

* Display a listing of the resource.

*

* @return \Illuminate\Http\Response

*/

public function addMorePost(Request $request)

{

$request->validate([

'addmore.*.name' => 'required',

'addmore.*.qty' => 'required',

'addmore.*.price' => 'required',

]);

foreach ($request->addmore as $key => $value) {

ProductStock::create($value);

}

return back()->with('success', 'Record Created Successfully.');

}

}

Step 6: Create Blade File

now we move in last step. In this step we have to create just addMore.blade.php blade file.

So let's just create following file and put bellow code.

resources/views/addMore.blade.php

<!DOCTYPE html>

<html>

<head>

<title>Add/remove multiple input fields dynamically with Jquery Laravel 5.8</title>

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>

</head>

<body>

<div class="container">

<h2 align="center">Add/remove multiple input fields dynamically with Jquery Laravel 5.8</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>Name</th>

<th>Qty</th>

<th>Price</th>

<th>Action</th>

</tr>

<tr>

<td><input type="text" name="addmore[0][name]" placeholder="Enter your Name" class="form-control" /></td>

<td><input type="text" name="addmore[0][qty]" placeholder="Enter your Qty" class="form-control" /></td>

<td><input type="text" name="addmore[0][price]" placeholder="Enter your 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+'][name]" placeholder="Enter your Name" class="form-control" /></td><td><input type="text" name="addmore['+i+'][qty]" placeholder="Enter your Qty" class="form-control" /></td><td><input type="text" name="addmore['+i+'][price]" placeholder="Enter your 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>

Now you can run this full example using quick run command of laravel like as bellow:

php artisan serve

Now you can open bellow URL on your browser:

http://localhost:8000/addmore

I hope it can help you...