Monday 15 April 2019

Dynamically Add / Remove input fields in Laravel 5.8 using jQuery Ajax



Hi, If you want to use Laravel 5.8 framework for your web development then here we have come with one more advance level of web development topic like How to Add or remove HTML input fields dynamically using jQuery and how to save multiple records in Laravel 5.8 by using Ajax. So, here we have share one more topic on Laravel 5.8 and in this part you can learn how to add more fields using jQuery in Laravel 5.8 application, and for validate dynamically generated input fields we have also implement validation on dynamic generated fields also by using Laravel 5.8 Validator class. So, if you have use Laravel 5.8 for website development purpose and if you add feature like insert or save multiple records at the same time in Laravel 5.8 with Ajax, then this post will help you because in this post we hvae step by step covered How to add or remove textbox dynamically with jQuery and then after by using Ajax with Laravel 5.8 we have save multiple records in Mysql database.

If you are web developer and then in web development we need to sometimes required to insert or save multiple records in Mysql database at the same time. For generate multiple records we want to make multiple fields, for generate dynamic multiple fields here we have use jquery as front-end with Laravel 5.8 application. One of our previous post, we have already covered Add or remove dynamic input fields by using jQuery with PHP. But here we need to do Add or remove dynamically generated fields in jQuery in Laravel 5.8 application. Because this is very useful feature in web application by doing multiple operation in single click or insert or save multiple data into mysql database in single click on Laravel 5.8 application. Here you can also learn how to validate multiple input fields data with same data in Laravel 5.8 validator class. And here also you can learn how to insert or save or add multiple data in Laravel 5.8 application.






Step 1 - Download Laravel 5.8


First we need to download Laravel 5.8 application. For this we have to go to command prompt and write following command. It will download Laravel 5.8 application in your define folder.


composer create-project laravel/laravel=5.8 ajax-crud --prefer-dist


Step 2 - Make Database connection


After install of Laravel 5.8 application, first we wanted to make Mysql database connection. For this you have to open .env file and in that file you have to define Mysql database configuration.


DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=testing
DB_USERNAME=root
DB_PASSWORD=


Step 3 - Create Table from Laravel 5.8


After making of Mysql database, now we want to create table in Mysql database from Laravel 5.8 application. For this we need to go to command prompt and write following command.


php artisan make:migration create_dynamic_field --create=dynamic_fields

This command will make migration file under database/migarations folder. In that file you have to define table column defination details, which you can find below.


<?php

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

class CreateDynamicField extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('dynamic_fields', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->string('first_name');
            $table->string('last_name');
            $table->timestamps();
        });
    }

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


Now we want to migrate above table defination from Laravel 5.8 application to Mysql database. For this we have to go to command prompt and write following command. This command will make dynamic_fields table under Mysql database.


php artisan migrate


Step 4 - Create Model


For create model under Laravel 5.8 application, we have to go to command prompt and write following command. This command will make DynamicField.php modal file under app folder.


php artisan make:model DynamicField -m


In app/DynamicField.php file we have to define table column name on which we need for database operation.


<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class DynamicField extends Model
{
    protected $fillable = [
        'first_name', 'last_name'
    ];
}





Step 5 - Create Controller


Controller is the heart of Laravel 5.8 application because it has handle all http request. First we want to make controller, so we have to go to command prompt and write following command. It will make DynamicFieldController.php file under app/Http/Controllers folder.


php artisan make:controller DynamicFieldController


In this controller file you can see below in which we have add two statement in the header. First is use App\DynamicField is for use DynamicField.php modal file use here and second Validator is for use Laravel 5.8 validator class for validate form data. In this controller we have make two method which you can see below.

index() - This is root method of this controller and it will load dynamic_field.blade.php file on web browser as an output.

insert() - This method has received ajax request for insert multiple data. Under this method first it has validate multiple form data of same name. So, here question aris how to validate multiple form data of same name in Laravel 5.8, so here we have add * sign with input field name, which has been used when we have validate multiple form data of the same name in Laravel 5.8 application. If suppose there is any form validation error has been occur then it will send validation error to ajax request in JSON format by using response() method. But suppose there is no any validation error occur then it will continue execute. After this there one more question aris how to insert multiple data in Laravel 5.8 application. So here we have store multiple data in local variable in array format and by using insert() method of modal class, it will insert or save multiple data in Laravel 5.8 application.


<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\DynamicField;
use Validator;

class DynamicFieldController extends Controller
{
    function index()
    {
     return view('dynamic_field');
    }

    function insert(Request $request)
    {
     if($request->ajax())
     {
      $rules = array(
       'first_name.*'  => 'required',
       'last_name.*'  => 'required'
      );
      $error = Validator::make($request->all(), $rules);
      if($error->fails())
      {
       return response()->json([
        'error'  => $error->errors()->all()
       ]);
      }

      $first_name = $request->first_name;
      $last_name = $request->last_name;
      for($count = 0; $count < count($first_name); $count++)
      {
       $data = array(
        'first_name' => $first_name[$count],
        'last_name'  => $last_name[$count]
       );
       $insert_data[] = $data; 
      }

      DynamicField::insert($insert_data);
      return response()->json([
       'success'  => 'Data Added successfully.'
      ]);
     }
    }
}


Step 6 - Create View file


In this post we have create dynamic_field.blade.php file under resources/views folder. Under this file for generate dynamic input field we have use jQuery code. By using jQuery here it will dynamically generate html input fields. For submit form data here we have use Ajax request, by using ajax request it will send form data to controller method.


<html>
 <head>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Laravel 5.8 - DataTables Server Side Processing using Ajax</title>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
 </head>
 <body>
  <div class="container">    
     <br />
     <h3 align="center">Dynamically Add / Remove input fields in Laravel 5.8 using Ajax jQuery</h3>
     <br />
   <div class="table-responsive">
                <form method="post" id="dynamic_form">
                 <span id="result"></span>
                 <table class="table table-bordered table-striped" id="user_table">
               <thead>
                <tr>
                    <th width="35%">First Name</th>
                    <th width="35%">Last Name</th>
                    <th width="30%">Action</th>
                </tr>
               </thead>
               <tbody>

               </tbody>
               <tfoot>
                <tr>
                                <td colspan="2" align="right">&nbsp;</td>
                                <td>
                  @csrf
                  <input type="submit" name="save" id="save" class="btn btn-primary" value="Save" />
                 </td>
                </tr>
               </tfoot>
           </table>
                </form>
   </div>
  </div>
 </body>
</html>

<script>
$(document).ready(function(){

 var count = 1;

 dynamic_field(count);

 function dynamic_field(number)
 {
  html = '<tr>';
        html += '<td><input type="text" name="first_name[]" class="form-control" /></td>';
        html += '<td><input type="text" name="last_name[]" class="form-control" /></td>';
        if(number > 1)
        {
            html += '<td><button type="button" name="remove" id="" class="btn btn-danger remove">Remove</button></td></tr>';
            $('tbody').append(html);
        }
        else
        {   
            html += '<td><button type="button" name="add" id="add" class="btn btn-success">Add</button></td></tr>';
            $('tbody').html(html);
        }
 }

 $(document).on('click', '#add', function(){
  count++;
  dynamic_field(count);
 });

 $(document).on('click', '.remove', function(){
  count--;
  $(this).closest("tr").remove();
 });

 $('#dynamic_form').on('submit', function(event){
        event.preventDefault();
        $.ajax({
            url:'{{ route("dynamic-field.insert") }}',
            method:'post',
            data:$(this).serialize(),
            dataType:'json',
            beforeSend:function(){
                $('#save').attr('disabled','disabled');
            },
            success:function(data)
            {
                if(data.error)
                {
                    var error_html = '';
                    for(var count = 0; count < data.error.length; count++)
                    {
                        error_html += '<p>'+data.error[count]+'</p>';
                    }
                    $('#result').html('<div class="alert alert-danger">'+error_html+'</div>');
                }
                else
                {
                    dynamic_field(1);
                    $('#result').html('<div class="alert alert-success">'+data.success+'</div>');
                }
                $('#save').attr('disabled', false);
            }
        })
 });

});
</script>


Step 7 - Set Route


In Laravel 5.8, we need to set route of all controller method which we have make. For this we have to open routes/web.php file and define following code for set route.


Route::get('dynamic-field', 'DynamicFieldController@index');

Route::post('dynamic-field/insert', 'DynamicFieldController@insert')->name('dynamic-field.insert');


Step 8 - Run Laravel 5.8 application


For run Laravel 5.8 application, we have to go to command prompt and write following command. This command will start Laravel 5.8 application and give you base url of your Laravel 5.8 application.


php artisan serve


For check output in browser you have to write following url in your browser tab.


http://127.0.0.1:8000/dynamic-field




14 comments:

  1. On pressing the save button, it doesnot saves the data in db. and the button freezes.

    ReplyDelete
  2. Can it be implemented with datataables?
    Would you give us a tutorial if possible

    ReplyDelete
  3. How can a page contain two forms having same functionality but data will be stored on different table ?

    ReplyDelete
  4. Hello my name is Abdulloh
    I am from Bukhara in Uzbekistan

    ReplyDelete
  5. di DynamicFieldController.php ada baris yang menunjukan DynamicField::insert() tetapi di file DynamicField.php tidak ada fungsi yang mendefinisikan metode insert()?

    ReplyDelete
  6. Nice tutorial, could you show for edit and update data..?

    ReplyDelete
  7. Excelente funciona a la perfección. Gracias !

    ReplyDelete
  8. Thank you this is work for me...

    ReplyDelete
  9. unfortunately couldn't get it to work. i guess because i am using 5.7?

    ReplyDelete
  10. i keep receiving Route not found even though i copied and pasted all the codes

    ReplyDelete
  11. I encountered a 500 internal error and save button was freezing.This is the changes I made on the Student Model file.Hope it helps.


    <?php

    namespace App\Models;

    use Illuminate\Database\Eloquent\Factories\HasFactory;
    use Illuminate\Database\Eloquent\Model;

    class Student extends Model
    {
    use HasFactory;

    protected $table = 'students';
    public $timestamps = true;

    protected $fillable = [
    'first_name',
    'last_name'
    ];

    }

    ReplyDelete