Laravel Ajax Multiple Delete Records using Checkbox Example

Laravel Ajax Multiple Delete Records using Checkbox Example

In web applications, sometimes we need to perform batch operations like deleting multiple records at once. This can be achieved easily with the help of checkboxes and AJAX requests. In this article, we will see how to implement the multiple delete operation using checkboxes and AJAX in Laravel.

Prerequisites

Before we begin, make sure you have the following:

  • PHP 7.x or later installed on your machine.
  • Composer installed on your machine.
  • Laravel 8.x or later installed on your machine.
  • A basic understanding of Laravel and jQuery.

Setup

First, we need to create a new Laravel project. Open your terminal and run the following command:

laravel new laravel-ajax-multiple-delete

Next, we need to create a database and configure the database credentials in the .env file. After that, run the migration command to create a new table:

php artisan make:migration create_users_table --create=users

Edit the newly created migration file and add the following code:

public function up()
{
    Schema::create('users', function (Blueprint $table) {
        $table->id();
        $table->string('name');
        $table->string('email')->unique();
        $table->timestamp('email_verified_at')->nullable();
        $table->string('password');
        $table->rememberToken();
        $table->timestamps();
    });
}

Next, run the migration command to create the users table:

php artisan migrate

Now, we need to create a new model and controller for the users table:

php artisan make:model User -mc

This command will create a new model and controller for the users table.

Implementation

Step 1: Create a Route

Open the web.php file located in the routes directory and add the following code:

Route::get('/', 'App\Http\Controllers\UserController@index');
Route::post('delete', 'App\Http\Controllers\UserController@delete');

Step 2: Create a View

Create a new file named index.blade.php in the resources/views directory and add the following code:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel Ajax Multiple Delete Records using Checkbox Example</title>
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0/css/bootstrap.min.css" />
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>
<body>
  
<div class="container mt-5">
    <h2>Laravel Ajax Multiple Delete Records using Checkbox Example</h2>
    <table class="table table-bordered">
        <thead>
            <tr>
                <th><input type="checkbox" id="check_all"></th>
                <th>ID</th>
                <th>Name</th>
                <th>Email</th>
                <th>Action</th>
            </tr>
        </thead>
        <tbody>
            @foreach($users as $user)
            <tr>
                <td><input type="checkbox" class="checkbox" data-id="{{ $user->id }}"></td>
                <td>{{ $user->id }}</td>
                <td>{{ $user->name }}</td>
                <td>{{ $user->email }}</td>
                <td><button class="btn btn-danger deleteBtn">Delete</button></td>
            </tr>
           

Step 2: Create a View (Continued)

        @endforeach
    </tbody>
</table>

<button class="btn btn-danger mb-3" id="bulk_delete">Delete Selected</button>

{{ $users->links() }}
</div>
<script>
    $(document).ready(function(){
      
        // Check or Uncheck All checkboxes
        $("#check_all").change(function(){
            var check_all = this.checked;
            $(".checkbox").each(function(){
                this.checked = check_all;
            });
        });
  
        // Delete button click
        $(".deleteBtn").click(function(){
            var id = $(this).closest("tr").find(".checkbox").data("id");
            delete_user(id);
        });
  
        // Bulk Delete button click
        $("#bulk_delete").click(function(){
            var id = [];
            $(".checkbox:checked").each(function(){
                id.push($(this).data("id"));
            });
            if(id.length > 0)
            {
                delete_user(id);
            }
            else
            {
                alert("Please select at least one record.");
            }
        });
      
        // Delete user function
        function delete_user(id)
        {
            if(confirm("Are you sure you want to delete this record?"))
            {
                $.ajax({
                    url: "{{ url('delete') }}",
                    type: "POST",
                    data: {
                        id: id,
                        _token: "{{ csrf_token() }}"
                    },
                    success: function(response) {
                        location.reload();
                    }
                });
            }
        }
      
    });
</script>
</body>
</html>

In this code, we have created a table that displays the list of users with checkboxes and a delete button for each record. We have also added a delete selected button that deletes all the selected records at once.

Step 3: Create a Controller

Open the UserController.php file located in the app/Http/Controllers directory and add the following code:

<?php
  
namespace App\Http\Controllers;
  
use Illuminate\Http\Request;
use App\Models\User;
use DB;
  
class UserController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index()
    {
        $users = User::latest()->paginate(10);
        return view('index', compact('users'));
    }
  
    /**
     * Remove the specified resource from storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function delete(Request $request)
    {
        $ids = $request->id;
        User::whereIn('id', $ids)->delete();
        return response()->json(['success'=>"Records deleted successfully."]);
    }
}

In this code, we have created two methods: index() and delete(). The index() method fetches the list of users from the database and passes it to the view. The delete() method receives the list of IDs to be deleted and deletes them from the database.

Conclusion

In this article, we have seen how to implement Laravel Ajax Multiple Delete Records using Checkbox Example. We have created a view that displays a list of users with checkboxes and a delete button for each record. We have also added a delete selected button that deletes all the selected records at once. We have used jQuery and AJAX to handle the delete operation.

This Article Ideas has been taken from the following websites; which are following:

https://www.itsolutionstuff.com/post/how-to-delete-multiple-records-using-checkbox-in-laravel-5-example.html

Laravel Ajax Multiple Delete Records using Checkbox

https://techsolutionstuff.com/post/how-to-delete-multiple-records-using-checkbox-in-laravel

https://www.javatpoint.com/delete-multiple-records-using-checkbox-in-laravel

Laravel Ajax Multiple Delete Records using Checkbox Example

How to Delete Multiple Records using Checkbox in Laravel?

https://www.nicesnippets.com/blog/laravel-delete-multiple-records-using-checkbox-example

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *