PHP Laravel Dynamically Add Remove Table Row

Today, We want to share with you PHP Laravel Dynamically Add Remove Table Row Using jQuery.In this post we will show you Dynamically add input fields and save data to Database in Laravel 5.7, hear for PHP Laravel 5.7 Dynamically Add Remove input fields using JQuery Ajax Example with Demo we will give you demo and example for implement.In this post, we will learn about Laravel 5.7 Insert Dynamic Images Arrays JQuery on Database in One Column with an example.

PHP Laravel Dynamically Add Remove Table Row Using jQuery

There are the Following The simple About PHP Laravel Dynamically Add Remove Table Row Using jQuery Full Information With Example and source code.

As I will cover this Post with live Working example to develop Laravel 5.7 Dynamically Add or Remove Table Row Using jQuery, so the Laravel – Dynamically Add or Remove input fields using JQuery for this example is following below.

Simple PHP Laravel 5.7 Dynamically Add Remove input fields using JQuery Ajax Example with Demo

Create catlists Table and Model

database/migrations

php artisan make:migration create_catslist_table

<?php
use Illuminate\Support\Facades\Schema;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;
class CreateCatslistTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('catlists', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->timestamps();
        });
    }
    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('catlists');
    }
}

php artisan migrate
php artisan make:model CatList

app/CatList.php
<?php
namespace App;
use Illuminate\Database\Eloquent\Model;
class CatList extends Model
{
    public $table = "catlists";
    public $fillable = ['name'];
}

Define Laravel Routes

routes/web.php

Route::get("addProduct","[email protected]");
Route::post("addProduct","[email protected]");

Create ProductController

php artisan make:controller ProductController

app/Http/Controllers/ProductController.php
<?php
namespace App\Http\Controllers;

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

class ProductController extends Controller
{

    public function addProduct()
    {
        return view("addProduct");
    }

    public function addProductMore(Request $request)
    {
        $rules = [];
        foreach($request->input('name') as $key => $value) {
            $rules["name.{$key}"] = 'required';
        }
        $validator = Validator::make($request->all(), $rules);

        if ($validator->passes()) {
            foreach($request->input('name') as $key => $value) {
                CatList::create(['name'=>$value]);
            }
            return response()->json(['success'=>'done']);
        }
        return response()->json(['error'=>$validator->errors()->all()]);
    }
}

Create Laravel Blade File

resources/views/addProduct.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Laravel 5.7 - Dynamically Add or Remove input fields using JQuery</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>
    <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 5.7 - Dynamically Add or Remove input fields using JQuery - Pakainfo.com</h2>  
    <div class="form-group">
         <form name="product_name" id="product_name">  
            <div class="alert alert-danger error-message-display" style="display:none">
            <ul></ul>
            </div>
            <div class="alert alert-success print-success-msg" style="display:none">
            <ul></ul>
            </div>
            <div class="table-responsive">  
                <table class="table table-bordered" id="dynamic_field">  
                    <tr>  
                        <td><input type="text" name="name[]" placeholder="Enter your Name" class="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>


<script type="text/javascript">
    $(document).ready(function(){      
      var postURL = "<?php echo url('addProduct'); ?>";
      var i=1;  

      $('#add').click(function(){  
           i++;  
           $('#dynamic_field').append('<tr id="row'+i+'" class="dynamic-added"><td><input type="text" name="name[]" placeholder="Enter your Product Name" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');  
      });  

      $(document).on('click', '.btn_remove', function(){  
           var button_id = $(this).attr("id");   
           $('#row'+button_id+'').remove();  
      });  


      $.ajaxSetup({
          headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
          }
      });


      $('#submit').click(function(){            
           $.ajax({  
                url:postURL,  
                method:"POST",  
                data:$('#product_name').serialize(),
                type:'json',
                success:function(data)  
                {
                    if(data.error){
                        previewMessage(data.error);
                    }else{
                        i=1;
                        $('.dynamic-added').remove();
                        $('#product_name')[0].reset();
                        $(".print-success-msg").find("ul").html('');
                        $(".print-success-msg").css('display','block');
                        $(".error-message-display").css('display','none');
                        $(".print-success-msg").find("ul").append('<li>Record Inserted Successfully.</li>');
                    }
                }  
           });  
      });  


      function previewMessage (msg) {
         $(".error-message-display").find("ul").html('');
         $(".error-message-display").css('display','block');
         $(".print-success-msg").css('display','none');
         $.each( msg, function( key, value ) {
            $(".error-message-display").find("ul").append('<li>'+value+'</li>');
         });
      }
    });  
</script>
</body>
</html>

Angular 6 CRUD Operations Application Tutorials

Read :

Summary

You can also read about AngularJS, ASP.NET, VueJs, PHP.

I hope you get an idea about PHP Laravel Dynamically Add Remove Table Row Using jQuery.
I would like to have feedback on my Pakainfo.com blog.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.


Related FAQ

Here are some more FAQ related to this Article:

  1.   How to get last inserted id in laravel 5.8?
  2.   How to Create, Access and Destroy Sessions in Asp.Net
  3.   Array push key value pair Dynamically in javascript
  4.   Filter (Search) Table using Angular Example
  5.   PHP Include and Require commands
  6.   install nodejs on Xampp localhost - setup node.js development environment
  7.   NodeJS RESTful API User Authentication with AngularJS using PHP MYSQL
  8.   jQuery Add and Remove Multiple Div Dynamically using PHP
  9.   install PHP Accelerator in Xampp - prestashop
  10.   ng-table Pagination using Angular Example