Skip to main content

Add and Remove Input Fields Dynamically with Jquery Laravel 5.8 | PHP | JayVitech

In this post we will learn how to "Add and Remove Input Fields Dynamically with Jquery Laravel 5.8".
Today, we add and remove input fields dynamically using jquery and save to the database in laravel 5.8 Project.
Dynamically add input fields are usefull when you add or clone same input fields to enter the different data into form. It is good option when you need to get multiple values of same field.
add image
So, let's start:

Watch Now Laravel 7 new Feature - Components

Step 1: Install Laravel 5.8 Project
Type the following command:
composer create-project --prefer-dist laravel/laravel dynamic-fields "5.8.*" 
Step 2: Database Configuration
In this step we configure the database. We put the database details like database name, username and password to store the data. open .env file into laravel project folder.
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=jayvitech (Your database name) DB_USERNAME=root (Your user name) DB_PASSWORD=

Step 3: Make a Database migration table and model
Using Laravel migration we create a table into database.
Type the following command to create a database table migration:
php artisan make:migration create_dynamic_fields_table
After this command go to the following path database/migrations and put bellow code in your migration file for create table.
<?php use Illuminate\Support\Facades\Schema; use Illuminate\Database\Schema\Blueprint; use Illuminate\Database\Migrations\Migration; class CreateDynamicFieldsTable extends Migration {     /**      * Run the migrations.      *      * @return void      */     public function up()     {         Schema::create('dynamic_fields'function (Blueprint $table) {             $table->bigIncrements('id');             $table->string('name');             $table->string('language');             $table->tinyInteger('age');             $table->timestamps();         });     }     /**      * Reverse the migrations.      *      * @return void      */     public function down()     {         Schema::dropIfExists('dynamic_fields');     } }
Type the following command to run migration:
php artisan migrate
After creating table we create a model for this table.
Type the following command to create a Model.
php artisan make:model DynamicFields
After that find a app/DynamicFields file and put below code:
<?php namespace App; use Illuminate\Database\Eloquent\Model; class DynamicFields extends Model {     public $fillable = ['name''language''age']; }

Step 4: Define the route name under the web.php file
Route::get("add-field", ['as' => 'dynamic_fields''uses' => 'DynamicFieldsController@addFields']); Route::post("add-field", ['as' => 'post_dynamic_fields''uses' => 'DynamicFieldsController@postAddFields']); Route::post("clone-fields", ['as' => 'clone_fields''uses' => 'DynamicFieldsController@getCloneFields']);

Step 5: Create a DynamicFieldsController
We create new controller name DynamicFieldsController by using
php artisan make:controller DynamicFieldsController;
This controller handle all route action. So, put bellow code into
app/Http/Controllers/DynamicFieldsController.php file:
<?php namespace App\Http\Controllers; use Illuminate\Http\Request; use App\DynamicFields; use Illuminate\Support\Facades\Input; class DynamicFieldsController extends Controller {     public function addFields() {         return view("dynamic-fields");     }     public function postAddFields(Request $request) {         $inputData = Input::except('_token');         for($i=0$i<count($inputData['name']); $i++) {             $data['name'] = $inputData['name'][$i];             $data['language'] = $inputData['language'][$i];             $data['age'] = $inputData['age'][$i];             $saveData = new DynamicFields($data);             $saveData->save();         }         return back()->with('success''Record Created Successfully.');     }     public function getCloneFields() {         $input = Input::all();         $id = $input['div_count'];         $varId = 'removeId'$id;         $data = '         <div class="clonedInput" id="'$varId .'">             <div class="row" id="clonedInput">                 <div class="col-md-3">                     <input type="text" name="name[]" id="name'$id .'" placeholder="Enter Your Name" class="form-control" required/>                     <label class="control-label col-md-8"></label>                 </div>                 <div class="col-md-3">                     <input type="text" name="language" id="language'$id .'" placeholder="Enter Your Language"  class="form-control" required/>                     <label class="control-label col-md-8"></label>                 </div>                 <div class="col-md-3">                     <input type="number" name="age[]" id="age'$id .'" placeholder="Enter Your Age"  class="form-control" required/>                     <label class="control-label col-md-8"></label>                 </div>                 <div class="col-md-1">                     <input type="button" class="btn btn-danger" name="del_item" value="Delete" onClick="removedClone('$varId .');" />                 </div>             </div>         </div>         ';         echo json_encode($data);     } }

Step 6: Create a dynamic-fields.blade.php
Last step is to create a dynamic-fields.blade.php under the (resources/views/dynamic-fields.blade.php) folder. we create a layout and design code into this file so write below code:
<!doctype html> <html lang="en">     <head>         <meta charset="utf-8">         <title>Add or Remove input fields dynamically with Jquery Laravel 5.8 demo</title>         <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no">         <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.0/css/bootstrap.min.css" integrity="sha384-SI27wrMjH3ZZ89r4o+fGIJtnzkAnFs3E4qz9DIYioCQ5l9Rd/7UAa8DHcaL8jkWt" crossorigin="anonymous">     </head>     <body>         <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>         <meta name="csrf-token" content="{{ csrf_token() }}" />         <div class="container">             <br><br>             <h2 style="text-align: center">Add or Remove input fields dynamically with Jquery Laravel 5.8 demo</h2>             <br><br>             @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             <form action="{{ route('post_dynamic_fields'}}" id="form_sample_1" method="post">                 @csrf                 <div class="col-md-12">                     <button onclick="createClone()" type="button" class="btn btn-success"><i class="fa fa-plus"></i> Add New</button>                     <br><br>                     <div class="clonedInput" id="removeId1">                         <div class="row" id="clonedInput">                             <div class="col-md-3">                                 <input type="text" name="name[]" id="name" placeholder="Enter Your Name" class="form-control" required/>                                 <label class="control-label col-md-8"></label>                             </div>                             <div class="col-md-3">                                 <input type="text" name="language" id="language" placeholder="Enter Your Language"  class="form-control" required/>                                 <label class="control-label col-md-8"></label>                             </div>                             <div class="col-md-3">                                 <input type="number" name="age[]" id="age" placeholder="Enter Your Age"  class="form-control" required/>                                 <label class="control-label col-md-8"></label>                             </div>                         </div>                     </div>                     <div class="row">                         <div class="col-md-offset-3 col-md-9">                             <button type="submit" class="btn btn-primary">Submit</button>                         </div>                     </div>                 </div>             </form>         </div>         <script type="text/javascript">             function createClone() {                 var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');                 $.ajax( {                     url: 'clone-fields',                     method: 'post',                     data: {'_token': CSRF_TOKEN'div_count': $('.clonedInput').length + 1},                 } ).successfunctiondata ) {                     var obj = JSON.parse(data);                     $('#clonedInput').before(obj);                 });             }             function removedClone(id){                 var r = confirm("Are you sure you want to delete?");                 if (r == true) {                     $(id).remove();                 }             }         </script>     </body> </html>

Step 7: Run Project
Finally we run project by following command:
 php artisan serve 
add remove image

See also How to Import and Export CSV or Excel file into Laravel 5.8
See also Image Compress demo in laravel 5.8
See also Laravel best Packages in 2020.

Conclusion
Using the Jquery and Bootstrap we create a demo of Add and Remove Input Fields Dynamically with Jquery Laravel 5.8. I hope this example help you to develop to create a multiple clone input fields into your laravel project.
So, Guys please Share PHP Artisan with Jay Chauhan Blog to your Technical friends and do the best coding with an easy way.
🙏🙏🙏💃💓

Comments


  1. Get all learn coding and programming Learn latest technology, software development skills, b.tech, MCA and BCA

    computer programming training.

    ReplyDelete
  2. This post of yours is very informative for any web developer. Looking forward to read more.
    Best Laravel Web Development Services

    ReplyDelete
  3. Hey Nice Blog!!! Thank you for sharing the information. Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!!!

    php website development company in delhi
    PHP Web Development services in noida
    php web development company

    ReplyDelete
  4. Tecocraft Ltd has been empowering for Web Development Company In UK and solutions for customers willing to grow their business and want to provide a great user experience to end users.

    ReplyDelete
  5. Nice articel, This article help me very well. Thank you. Also please check my article on my site Know All About Deprecated: Non-Static Method Templates::Override_tax_template().

    ReplyDelete
  6. Great Post with valuable information. Thank you for the knowledge.
    PHP Online Classes
    online php course with certificate

    ReplyDelete
  7. Hey Nice Blog!!! Thank you for sharing the information. Wonderful blog & good post.Its really helpful for me, waiting for a more new post. Keep Blogging!!!
    white label website builder

    website builder for reseller

    ReplyDelete
  8. As a top PHP Development Company in New York we found this blog very informative, Keep sharing your knowledge.

    ReplyDelete

Post a Comment

Show Latest Post

Laravel 5.8 Digital Signature - Signature Pad | Jquery signature pad | JayviTech

In this post we can learn how to make Digital  Signature Pad  into your Laravel 5.8 project. Using the JavaScript Library we can draw the smooth signatures, It is a HTML5 Canvas based. It is working for all modern browsers, desktop and mobile browsers. Signature Pad Watch  What is MVC Structure? Watch to learn:  Laravel 7 Tutorial We create a Digital E-Signature Pad with saving as a image using HTML5 canvas. So, Let's start: Step 1: Install Laravel 5.8 Project Type the following command. composer create-project --prefer-dist laravel/laravel blog "5.8.*" Step 2: Define the route name under the web.php file Route :: get ( '/signature-pad' ,  function  () {      return   view ( 'signature-pad' ); }); Step 3: Create a Signature Pad Now we can create a Signature Pad view, then after we can watch how our signature pad look like into our Laravel project. Create a  signature-pad.blade....

Image Compress demo in laravel 5.8 | Intervention Image - Resize image | JayviTech

In this post we will learn "How to compress image before upload in laravel 5.8" . We use intervention in laravel for compress a image. using a Laravel intervention we can easily compress a any type of image format. Intervention image package allows a image to compress and resize in laravel project. So, let's start: Step 1: Install Laravel 5.8 Project Type the following command. composer create-project --prefer-dist laravel/laravel blog "5.8.*" Step 2:  Install Intervention Image We will install intervention/image package for resize image. Using this package we can make thumbnail image. Type the following command: composer require intervention/image Then open  config/app.php  file and add service provider and aliase name. 'providers' => [ .... Intervention\Image\ImageServiceProvider::class, ], 'aliases' => [ .... 'Image' => Intervention\Image\Facades\Image::class, ], Then after publi...