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.
So, let's start:
Watch Now Laravel 7 new Feature - Components
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.
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.
Step 3: Make a Database migration table and model
Step 4: Define the route name under the web.php file
Step 5: Create a DynamicFieldsController
Step 6: Create a dynamic-fields.blade.php
Step 7: Run Project
Finally we run project by following command:
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
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:
After this command go to the following path database/migrations and put bellow code in your migration file for create table.Type the following command to create a database table migration:
php artisan make:migration create_dynamic_fields_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.
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 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},
} ).success( function( data ) {
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
php artisan serve
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.
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.
🙏🙏🙏💃💓
ReplyDeleteGet all learn coding and programming Learn latest technology, software development skills, b.tech, MCA and BCA
computer programming training.
This post of yours is very informative for any web developer. Looking forward to read more.
ReplyDeleteBest Laravel Web Development Services
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!!!
ReplyDeletephp website development company in delhi
PHP Web Development services in noida
php web development company
It is useful.. Learn Free Node.js coding tutorial
ReplyDeleteStay connect and always welcome
ReplyDeleteThis is the best tutorial for laravel development. Web design Services in Laravel @ $25 only
ReplyDeleteTecocraft 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.
ReplyDeleteNice 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().
ReplyDeleteGreat Post with valuable information. Thank you for the knowledge.
ReplyDeletePHP Online Classes
online php course with certificate
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!!!
ReplyDeletewhite label website builder
website builder for reseller
As a top PHP Development Company in New York we found this blog very informative, Keep sharing your knowledge.
ReplyDelete