Php how to delete multiple rows through checkbox using ajax in laravel

Php how to delete multiple rows through checkbox using ajax in laravel

If there are numbers of records available in the grid and you want to delete some of them then you have two ways to delete these records. One is that you can delete one by one but it will take long time to delete records and in the second way you can delete multiple rows through checkbox using ajax in laravel.

So here in this article i will give an example to delete multiple rows through checkbox using ajax in laravel.

Since deleting a record is a priviledged task, so we can not allow to delete records in a single click. It’s a good thing to ask confirmation before deleting.

So here, in this example, we will implement to ask confirmation before deleting a record. I am assuming you have already installed laravel application in your system.

Step 1: Create Table and Model

First thing, we will need a table and i am creating products table for this example. So run the following query to create table.

CREATE TABLE `products` (
 `id` int(10) unsigned NOT NULL AUTO_INCREMENT,
 `name` varchar(255) COLLATE utf8mb4_unicode_ci NOT NULL,
 `description` varchar(255) COLLATE utf8mb4_unicode_ci DEFAULT NULL,
 `created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
 `updated_at` datetime DEFAULT NULL,
 PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci

Next, we will need to insert some dummy records in this table that will be deleted.

INSERT INTO `products` (`name`, `description`) VALUES

('Test product 1', 'Product description example1'),

('Test product 2', 'Product description example2'),

('Test product 3', 'Product description example3'),

('Test product 4', 'Product description example4'),

('Test product 5', 'Product description example5');

Now we are redy to create a model corresponding to this products table. Here we will create Product model. So let’s create a model file Product.php file under app directory and put the code below.

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'name','description'
    ];
}

Step 2: Create Route

Now, in this second step we will create some routes to handle the request for this example. So opeen routes/web.php file and copy the routes as given below.

routes/web.php

Route::get('product', 'ProductController@index');
Route::delete('product/{id}', ['as'=>'product.destroy','uses'=>'ProductController@destroy']);
Route::delete('delete-multiple-product', ['as'=>'product.multiple-delete','uses'=>'ProductController@deleteMultiple']);

Step 3: Create Controller

In this step, we will create ProductController.php file under app/Http/Controllers directory and put the following code into this file.

app/Http/Controllers/ProductController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Product;

class ProductController extends Controller
{
    
    public function index(Request $request){
        $products=Product::get();
        return view('products',compact('products'));
    }

    public function destroy(Request $request,$id){
        $product=Product::find($id);
        $product->delete();
        return back()->with('success','Product deleted successfully');
    }   

    public function deleteMultiple(Request $request){
        $ids = $request->ids;
        Product::whereIn('id',explode(",",$ids))->delete();
        return response()->json(['status'=>true,'message'=>"Product deleted successfully."]);
        
    }

}

Step 4: Create View

Now, in this step we will create view for product listing where we will perform multiple delete. We will implement jquery ajax functionality to delete multiple records with confirmation funcationlity. So let’s create products.blade.php file and put the following code.

resources/views/products.blade.php

<!DOCTYPE html>
<html>
<head>
    <title>Php how to delete multiple rows through checkbox using ajax in laravel</title>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-confirmation/1.0.5/bootstrap-confirmation.min.js"></script>
    <meta name="csrf-token" content="{{ csrf_token() }}">

</head>
<body>


<div class="container">
    <h3>Php how to delete multiple rows through checkbox using ajax in laravel</h3>
    @if ($message = Session::get('success'))
    <div class="alert alert-success">
        <p>{{ $message }}</p>
    </div>
    @endif
    <button style="margin: 5px;" class="btn btn-danger btn-xs delete-all" data-url="">Delete All</button>
    <table class="table table-bordered">
        <tr>
            <th><input type="checkbox" id="check_all"></th>
            <th>S.No.</th>
            <th>Name</th>
            <th>Description</th>
            <th width="100px">Action</th>
        </tr>
        @if($products->count())
            @foreach($products as $key => $product)
                <tr id="tr_{{$product->id}}">
                    <td><input type="checkbox" class="checkbox" data-id="{{$product->id}}"></td>
                    <td>{{ ++$key }}</td>
                    <td>{{ $product->name }}</td>
                    <td>{{ $product->description }}</td>
                    <td>
                        {!! Form::open(['method' => 'DELETE','route' => ['product.destroy', $product->id],'style'=>'display:inline']) !!}

                            {!! Form::button('Delete', ['class' => 'btn btn-danger btn-xs','data-toggle'=>'confirmation','data-placement'=>'left']) !!}

                        {!! Form::close() !!}
                    </td>
                </tr>
            @endforeach
        @endif
    </table>
</div> 

</body>

<script type="text/javascript">
    $(document).ready(function () {

        $('#check_all').on('click', function(e) {
         if($(this).is(':checked',true))  
         {
            $(".checkbox").prop('checked', true);  
         } else {  
            $(".checkbox").prop('checked',false);  
         }  
        });

         $('.checkbox').on('click',function(){
            if($('.checkbox:checked').length == $('.checkbox').length){
                $('#check_all').prop('checked',true);
            }else{
                $('#check_all').prop('checked',false);
            }
         });

        $('.delete-all').on('click', function(e) {


            var idsArr = [];  
            $(".checkbox:checked").each(function() {  
                idsArr.push($(this).attr('data-id'));
            });  


            if(idsArr.length <=0)  
            {  
                alert("Please select atleast one record to delete.");  
            }  else {  

                if(confirm("Are you sure, you want to delete the selected products?")){  

                    var strIds = idsArr.join(","); 

                    $.ajax({
                        url: "{{ route('product.multiple-delete') }}",
                        type: 'DELETE',
                        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                        data: 'ids='+strIds,
                        success: function (data) {
                            if (data['status']==true) {
                                $(".checkbox:checked").each(function() {  
                                    $(this).parents("tr").remove();
                                });
                                alert(data['message']);
                            } else {
                                alert('Whoops Something went wrong!!');
                            }
                        },
                        error: function (data) {
                            alert(data.responseText);
                        }
                    });


                }  
            }  
        });

        $('[data-toggle=confirmation]').confirmation({
            rootSelector: '[data-toggle=confirmation]',
            onConfirm: function (event, element) {
                element.closest('form').submit();
            }
        });   
    
    });
</script>


</html>

Now, you have successfully completed multiple delete records in laravel application using jquery and ajax.

Learn laravel autocomplete search box using typehead and ajax by clicking on the link given below.

Laravel autocomplete search box using typeahead and ajax