Delete Multiple Records With Checkbox Example in Laravel 11

May 08, 2024 | PHP jQuery MySql Bootstrap Javascript Ajax Laravel 11


Hello Dev,

It's essential to provide users with the ability to remove multiple records using checkboxes, especially in large-scale web applications like e-commerce platforms. Today, I'll demonstrate how to implement this feature in Laravel versions 5 through 11. We'll cover both single and multiple record deletion functionalities.

If you haven't already, take a look at my previous post on adding a confirmation step before deleting a record in Laravel 5, which complements this example.

In this demonstration, I've set up a "products" table in the database, featuring columns such as id, name, details, created_at, and updated_at. Additionally, I've included a MySQL query to insert dummy records for testing purposes. To facilitate multiple record deletion, I'll utilize jQuery for selecting all checkboxes and deleting the corresponding records.

By following a few straightforward steps, you'll be able to integrate this functionality seamlessly into your Laravel application. Let's proceed to implement this feature and achieve the desired layout.

To implement a feature for deleting multiple records with checkboxes in a Laravel application, you can follow these steps. This guide will cover the process for Laravel versions 5 through 11, as requested. The approach involves creating a form with checkboxes for each record, handling the form submission on the server side to delete the selected records, and using jQuery for selecting all checkboxes.

Read Also: PHP MySQL Confirmation Box Before Delete Record Using Ajex Example Tutorial Step 1: Create a Form with Checkboxes

Assuming you have a table named products with columns id, name, details, created_at, and updated_at, you would first create a Blade template (e.g., resources/views/products/index.blade.php) that lists all products with a checkbox next to each one.

<!DOCTYPE html>
<html>
<head>
    <title>Delete Multiple Records With Checkbox Example in Laravel 11 -- ItErrorSolution.com</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>Delete Multiple Records With Checkbox Example in Laravel 11 -- ItErrorSolution.com</h3>
    <button style="margin-bottom: 10px" class="btn btn-primary delete_all" data-url="{{ url('myproductsDeleteAll') }}">Delete All Selected</button>
    <table class="table table-bordered">
        <tr>
            <th width="50px"><input type="checkbox" id="master"></th>
            <th width="80px">No</th>
            <th>Product Name</th>
            <th>Product Details</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="sub_chk" data-id="{{$product->id}}"></td>
                    <td>{{ ++$key }}</td>
                    <td>{{ $product->name }}</td>
                    <td>{{ $product->details }}</td>
                    <td>
                         <a href="{{ url('myproducts',$product->id) }}" class="btn btn-danger btn-sm"
                           data-tr="tr_{{$product->id}}"
                           data-toggle="confirmation"
                           data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
                           data-btn-ok-class="btn btn-sm btn-danger"
                           data-btn-cancel-label="Cancel"
                           data-btn-cancel-icon="fa fa-chevron-circle-left"
                           data-btn-cancel-class="btn btn-sm btn-default"
                           data-title="Are you sure you want to delete ?"
                           data-placement="left" data-singleton="true">
                            Delete
                        </a>
                    </td>
                </tr>
            @endforeach
        @endif
    </table>
</div> <!-- container / end -->
</body>
<script type="text/javascript">
    $(document).ready(function () {
        $('#master').on('click', function(e) {
         if($(this).is(':checked',true))  
         {
            $(".sub_chk").prop('checked', true);  
         } else {  
            $(".sub_chk").prop('checked',false);  
         }  
        });
        $('.delete_all').on('click', function(e) {
            var allVals = [];  
            $(".sub_chk:checked").each(function() {  
                allVals.push($(this).attr('data-id'));
            });  
            if(allVals.length <=0)  
            {  
                alert("Please select row.");  
            }  else {  
                var check = confirm("Are you sure you want to delete this row?");  
                if(check == true){  
                    var join_selected_values = allVals.join(","); 
                    $.ajax({
                        url: $(this).data('url'),
                        type: 'DELETE',
                        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                        data: 'ids='+join_selected_values,
                        success: function (data) {
                            if (data['success']) {
                                $(".sub_chk:checked").each(function() {  
                                    $(this).parents("tr").remove();
                                });
                                alert(data['success']);
                            } else if (data['error']) {
                                alert(data['error']);
                            } else {
                                alert('Whoops Something went wrong!!');
                            }
                        },
                        error: function (data) {
                            alert(data.responseText);
                        }
                    });
                  $.each(allVals, function( index, value ) {
                      $('table tr').filter("[data-row-id='" + value + "']").remove();
                  });
                }  
            }  
        });
        $('[data-toggle=confirmation]').confirmation({
            rootSelector: '[data-toggle=confirmation]',
            onConfirm: function (event, element) {
                element.trigger('confirm');
            }
        });
        $(document).on('confirm', function (e) {
            var ele = e.target;
            e.preventDefault();
            $.ajax({
                url: ele.href,
                type: 'DELETE',
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                success: function (data) {
                    if (data['success']) {
                        $("#" + data['tr']).slideUp("slow");
                        alert(data['success']);
                    } else if (data['error']) {
                        alert(data['error']);
                    } else {
                        alert('Whoops Something went wrong!!');
                    }
                },
                error: function (data) {
                    alert(data.responseText);
                }
            });
            return false;
        });
    });
</script>
</html>
Step 2: Define Routes

In your routes/web.php file, define a route for the mass delete action.

routes/web.php
 
Route::get('myproducts', 'ProductController@index');
Route::delete('myproducts/{id}', 'ProductController@destroy');
Route::delete('myproductsDeleteAll', 'ProductController@deleteAll');
Step 3: Implement the Controller Method

In your ProductController, implement the massDelete method to handle the deletion of multiple records.

app/Http/Controllers/ProductController.php
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use DB;

class ProductController extends Controller
{
    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $products = DB::table("products")->get();
        return view('products',compact('products'));
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        DB::table("products")->delete($id);
        return response()->json(['success'=>"Product Deleted successfully.", 'tr'=>'tr_'.$id]);
    }

    /**
     * Show the application dashboard.
     *
     * @return \Illuminate\Http\Response
     */
    public function deleteAll(Request $request)
    {
        $ids = $request->ids;
        DB::table("products")->whereIn('id',explode(",",$ids))->delete();
        return response()->json(['success'=>"Products Deleted successfully."]);
    }
}
Read Also: PHP MySQL Confirmation Box Before Delete Record Using Ajex Example Tutorial Step 4: Add Dummy Records (Optional)

If you want to add dummy records for testing, you can do so in a seeder or directly in the database. Here's how you might add a few records using a seeder:

 
use Illuminate\Database\Seeder;

class ProductsTableSeeder extends Seeder
{
    public function run()
    {
        DB::table('products')->insert([
            ['name' => 'Product 1', 'details' => 'Details 1'],
            ['name' => 'Product 2', 'details' => 'Details 2'],
            // Add more products as needed
        ]);
    }
}
Run the seeder with php artisan db:seed.

Conclusion

This guide provides a basic implementation for deleting multiple records with checkboxes in a Laravel application. You can extend this functionality by adding features such as confirmation dialogs, bulk editing, or integrating with other parts of your application. Remember to adjust the database model and controller names according to your application's structure.

Step: Run the Application

Now, to run the Laravel application, please type the following command and press enter:

php artisan serve

Now, open your web browser and enter the provided URL to view the output of the application.

View Your Application
http://localhost:8000/myproducts
Output: Delete Multiple Records With Checkbox Example in Laravel 11

Thank you for your encouragement! If you have any questions or need further assistance, feel free to ask. I'm here to help!



Tags :
#PHP
#jQuery
#MySql
#Bootstrap
#Javascript
#Ajax
#Laravel 11
#Laravel
ItErrorSolution.com

ItErrorSolution.com

"Hey there! I'm a full-stack developer and proud owner of ItErrorSolution.com, based right here in India. I love nothing more than sharing handy tips and tricks with my fellow developers through easy-to-follow tutorials. When it comes to coding, I'm all about PHP, Laravel, Angular, Vue, Node, JavaScript, jQuery, CodeIgniter, and Bootstrap – been hooked on them forever! I'm all about putting in the work and staying committed. Ready to join me on this journey to coding?"