Add Remove input fields Dynamically using Laravel

Add Remove input fields Dynamically using Laravel

In this Post We Will Explain About is Add Remove input fields Dynamically using Laravel With Example and Demo.Welcome on Live24u.com – Examples, The best For Learn web development Tutorials,Demo with Example! Hi Dear Friends here u can know to Laravel – Dynamically Add or Remove input fields using JQuery Example

In this post we will show you Best way to implement add field dynamically to form in jquery and Laravel, hear for dynamically add input fields and submit to database with jquery and Laravel with Download .we will give you demo,Source Code and examples for implement Step By Step Good Luck!.




Phase 1 : Install Laravel Application

I am going to Display We Basic Learn Laravel Full Example, Therefore we require to get Latest current Laravel 5.5 version for web application using bellow source CMD(Prompt), Therefore First of all the open terminal OR CMD(Prompt) prompt and Execute bellow source CMD(Prompt):

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

Phase 2: Database Configuration

In this Phase we have to make laravel using mysql database cofig/setting for Simple set all .env file (atmiya25)database name, (atmiya/root)username, (“blank”)password etc for simple web application of laravel 5.5. Therefore first of all open .env file and fill all the Information like as bellow source:

.env file in root

DB_CONNECTION=mysql
DB_HOST=YOUR_HOST_NAME(localhost)
DB_PORT=3306
DB_DATABASE=here your database name(live24u)
DB_USERNAME=YOUR_USER_NAME
DB_PASSWORD=YOUR_PASSWORD_DATABASE_SET

Phase 3: Make multitag Table and Model

I am going to make Laravel Add and Remove dynamic field web-application for multitag. Therefore we have to make database migration for multitag table using Laravel 5.5 web-application php artisan CMD(Prompt), Therefore Simple fire bellow run CMD(Prompt):

Also Read :   Laravel Add Remove input fields Dynamically using jQuery

php artisan make:migration create_multitag_table

Let’s this CMD(Prompt) We will Search this file in Baisc path Like as a database/migrations and We have to put this file to bellow source code in your migration generated file for make multitag table.

<?php
//use all the include
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateMultipleTagTable extends Migration
{
    public function up()
    {
        Schema::create('multitag', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }
    public function down()
    {
        Schema::dropIfExists('multitag');
    }
}

In this commands. Execute migration to my following some script CMD(Prompt):

php artisan migrate

And Making a table we have to make model for “multitag” table Therefore simple run or Execute bellow source CMD(Prompt) and make new model:

php artisan make:model MultiTag

After that Execute bellow source CMD(Prompt) We will Search app/MultiTag.php and put bellow some source All the code in MultiTag.php file:

app/MultiTag.php

<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class MultiTag extends Model
{
    public $table = "multitag";
    public $fillable = ['name'];
}

Phase 4: PUT Routes

In That is Phase we need to add two route for add more HTML Dyemically add fields Demo. Therefore First open your simple route routes/web.php file and Put following all the route.

routes/web.php

Route::get("moreadd","LiveController@moreAdd");
Route::post("moreadd","LiveController@MoreAddPost");

Phase 5: Make LiveController

we should make new controller as LiveController if We have not build. Therefore Execute bellow source CMD(Prompt) and Make new controller. bellow source laravel controller for Make resource model and controller.

Also Read :   Laravel vuejs form validation - Input Validation with Laravel

php artisan make:controller LiveController

After that bellow some source CMD(Prompt) We will Search new file in that path app/Http/Controllers/LiveController.php.

In that Laravel simple controller will make seven some default methods bellow source methods:

  • 1)moreAdd()
  • 2)MoreAddPost()

Therefore, Going to copy Past bellow source code and put on LiveController.php simple Laravel file.

app/Http/Controllers/LiveController.php

<?php

//include all namespace
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\MultiTag;
use Validator;
class LiveController extends Controller
{
    public function moreAdd()
    {
        return view("moreAdd");
    }
    public function MoreAddPost(Request $request)
    {
        $rules = [];
		//using loop get key all required fields
        foreach($request->input('name') as $key => $value) {
            $rules["name.{$key}"] = 'required';
        }
		//laravel validator all fields
        $validator = Validator::make($request->all(), $rules);
        if ($validator->passes()) {
			// all get key and value
            foreach($request->input('name') as $key => $value) {
                MultiTag::create(['name'=>$value]);
            }
			//return
            return response()->json(['success'=>'done']);
        }
        return response()->json(['error'=>$validator->errors()->all()]);
    }
}

Phase 6: Create Blade File

And we arrived in last Phase. In this last Phase we have to make just moreAdd.blade.php blade file.Therefore let’s just make file and put bellow source code.

resources/views/moreAdd.blade.php

<!DOCTYPE html>
<html>
<head>
<title>Laravel Add Remove input fields dynamically using jQuery</title>
<!-- bootstrap.min.css -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />  
<!-- jquery.min.js -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<!-- bootstrap.min.js -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="container">
    <h2 align="center">Laravel Add Remove input fields dynamically using jQuery</h2>  
    <div class="form-group">
         <form name="add_name" id="add_name">  
            <div class="alert alert-danger display-err-msg" style="display:none">
            <ul></ul>
            </div>
            <div class="alert alert-success display-success-msg" style="display:none">
            <ul></ul>
            </div>
            <div class="table-responsive">  
                <table class="table table-bordered" id="laravel_dynemic">  
                    <tr>  
                        <td><input type="text" name="name[]" placeholder="Please Eneter Good Name" class="live form-control name_list" /></td>  
                        <td><button type="button" name="add" id="add" class="btn btn-success">Add More</button></td>  
                    </tr>  
                </table>  
                <input type="button" name="submit" id="submit" class="btn btn-info" value="Submit" />  
            </div>
         </form>  
    </div> 
</div>
<!-- Devloped by http://live24u.com free download examples -->
<script type="text/javascript">
    $(document).ready(function(){      
      var postURL = "<?php echo url('moreadd'); ?>";
      var i=1;  
      $('#add').click(function(){  
           i++;  
           $('#laravel_dynemic').append('<tr id="row'+i+'" class="added-dynamic"><td><input type="text" name="name[]" placeholder="Please Eneter Good Name" class="live form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger remove_btn">X</button></td></tr>');  
      });  
      $(document).on('click', '.remove_btn', function(){  
           var btn_id = $(this).attr("id");   
           $('#row'+btn_id+'').remove();  
      });  
      $.ajaxSetup({
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });
      $('#submit').click(function(){            
           $.ajax({  
                url:postURL,  
                method:"POST",  
                data:$('#add_name').serialize(),
                type:'json',
                success:function(data)  
                {
                    if(data.error){
                        displayMsgErr(data.error);
                    }else{
                        i=1;
                        $('.added-dynamic').remove();
                        $('#add_name')[0].reset();
                        $(".display-success-msg").find("ul").html('');
                        $(".display-success-msg").css('display','block');
                        $(".display-err-msg").css('display','none');
                        $(".display-success-msg").find("ul").append('<li>Your Record Inserted Successfully.</li>');
                    }
                }  
           });  
      });  
      function displayMsgErr (msg) {
         $(".display-err-msg").find("ul").html('');
         $(".display-err-msg").css('display','block');
         $(".display-success-msg").css('display','none');
         $.each( msg, function( key, value ) {
            $(".display-err-msg").find("ul").append('<li>'+value+'</li>');
         });
      }
    });  
</script>
</body>
</html>

Now I am All the source code ready to execute simple captcha code example so execute bellow source CMD(Prompt) for quick way execute:

Also Read :   PHP SEND mail with Multiple Attachments

php artisan serve

After That Last Phase to run project you can open this bellow Web URL on your any browser:

http://localhost:8000/moreadd

You are Most welcome in my youtube Channel Please subscribe my channel. and give me FeedBack.
More Details……
Angularjs Example





Example

I hope you have Got What is Laravel dynamically add input fields and submit to database And how it works.I would Like to have FeedBack From My Blog(live24u.com) readers.Your Valuable FeedBack,Any Question,or any Comments about This Article(live24u.com) Are Most Always Welcome.