delete multiple rows at once in laravel 10

Delete multiple rows at once in laravel 10

In this article, I will show you, how to delete multiple records or rows in laravel 10.

In larger projects and extensive lists of records, we need to delete multiple rows at once in laravel 10, therefore I am writing this article for you Devs.

Fortunately, javascript made it easy to overcome this problem.

Here, I will implement this functionality on the list of users.

delete multiple rows at once in laravel 10
Selecting multiple rows at once in laravel 10

As you can see in the image, you can select multiple rows or check all rows at once.

Please follow the steps

Step 1: Install Laravel

First, install laravel 10 using the below command

create-project laravel/laravel deleterows --prefer-dist

Step 2: Set up database configuration

After installing laravel 10, go to your php myAdmin and create a database by the name of deleterows

After creating your database, open your project’s root directory, open the .env file, and paste the following code into it.

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

Step 3: Create Dummy Data for Datase

To play with the records we need to create some dummy or real data first, here I am going to create some dummy data for this example.

I will use laravel factory to create some dummy data.

Use the following commands to open the tinker command tool and create dummy data in the table.

php artisan tinker
User::factory()->count(30)->create() 

The above command will create 30 random and dummy records of users.

Step 4: Create a Controller

Now, let’s create a controller by the name of UsersController. To create UsesController use the below command.

php artisan make:controller UsersController

This command will create a controller file in “App/Http/Controllers” directory. Open the file and paste the below command into it.

UsersController.php

<?php

namespace App\Http\Controllers;

use App\Models\User;
use Illuminate\Http\Request;

class UsersController extends Controller
{
    //
    public function index()
    {
        $users = User::latest()->get();

        return view('users', compact('users'));
    }
    public function action(Request $request)
    {
        $ids = $request->id;

        $result = User::whereIn('id', explode(",", $ids))->delete();
        if ($result != null) {
            
            return 1;

        } else {

            return 0;

        }
    }
}

Where:

  • The ids variable is the array of data that the user will pass to the controller
  • We will get the advantage of laravel eloquent to delete multiple rows at once in laravel 10.
User::whereIn('id', explode(",", $ids))->delete();
  • Here firstly we will explode the ids array by the comma and check one by one and delete them.
  • Then we will check if any row is deleted. if deleted we will return 1 else 0.

Step 5: Create a view file

For listing our records, we need to create a view file. To create a view file, go to the “resources/views” path of your project, and create a file by the name of users.blade.php. Open the file and paste the following codes into it.

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Ajax Search in Laravel 10</title>
 <script src="https://code.jquery.com/jquery-3.6.0.min.js" crossorigin="anonymous"></script>
 <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery-validate/1.19.1/jquery.validate.min.js"></script>
 <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.3.0/css/all.min.css">

</head>

<body>

 <div class="container table-responsive py-5">
  <div class="row">
   <div class="col-12">

    <h2><a href="#" class="btn btn-danger btn-xs pull-right delete_all"><i class="fa fa-trash"></i> Delete All Selected Row/s</a> Laravel 10 Delete Multiple Rows </h2>
   </div>
   <div class="col-12">

    <table class="table table-striped custab">
     <thead>

      <tr>
       <th><input type="checkbox" name="search" id="selectAll"></th>
       <th>ID</th>
       <th>Full Name</th>
       <th>Email</th>
      </tr>
     </thead>
     @foreach($users as $user)
     <tr data-row-id="{{$user->id}}">
      <td><input type="checkbox" data-id="{{$user->id;}}" class="row_check"></td>
      <td>{{$user->id}}</td>
      <td>{{$user->name}}</td>
      <td>{{$user->email}}</td>
     </tr>
     @endforeach
    </table>
   </div>
  </div>
  <br>
 </div>
 <script>
  $(document).ready(function() {

   $('#selectAll').on('click', function(e) {

    //check and uncheck all rows
    if ($(this).is(':checked', true)) {
     $(".row_check").prop('checked', true);
    } else {
     $(".row_check").prop('checked', false);
    }
   });
   //take actioin of seelected rows
   $('.delete_all').on('click', function(e) {
    var allVals = [];
    $(".row_check:checked").each(function() {
     allVals.push($(this).attr('data-id'));
    });

    if (allVals.length <= 0) {
     alert("Please select at least one record");
    } else {

     var check = confirm("Are you sure of deleteting selected rows.");
     if (check == true) {

      var join_selected_values = allVals.join(",");
      console.log(join_selected_values);
      $.ajax({
       url: "{{ route('ajax_search.action') }}",

       type: 'POST',
       data: {
        "_token": "{{ csrf_token() }}",
        "id": join_selected_values,

       },
       success: function(data) {
        if (data == 1) {
         console.log('111');
         alert("Record has been deleted successfully!");
        }
        if (data == 0) {
         alert('There was an error deleting rows!')
        }
        $(".row_check:checked").each(function() {
         $(this).parents("tr").remove();
        });

       },
       error: function(data) {
        alert(data);
       }
      });

      $.each(allVals, function(index, value) {
       $('table tr').filter("[data-row-id='" + value + "']").remove();
      });
     }
    }
   });


  });
 </script>
</body>

</html>

Key points:

  • By clicking the check box of the table header with the id of selectAll we will check if all rows with the class of row_check are checked, we will uncheck them, if are unchecked we will check them by the power of JavaScript.
  • By clicking the Delete button we will get the id of each row which is defined as the data-id custom property for each row and push them to the allVals variable.
  • If allVals variable length was greater than 0 we will submit the ids to the controller with ajax.
  • As you can see in the success part of ajax request, we will remove records that were checked to be deleted from the list.
  • Remember to pass the token to the controller if your submission method is POST.

Step 6: Create routes

Here we will need two routes, one for listing our records and one for submitting the id of the record via ajax request.

Go to the “routes” directory in your project and open web.php file and paste the following codes into it.

<?php

use App\Http\Controllers\UsersController;
use Illuminate\Support\Facades\Route;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| Here is where you can register web routes for your application. These
| routes are loaded by the RouteServiceProvider and all of them will
| be assigned to the "web" middleware group. Make something great!
|
*/

Route::get('/', function () {
    return view('welcome');
});
Route::get('users-list', [UsersController::class, 'index'])->name('users-list');
Route::post('/ajax_search/action', [UsersController::class, 'action'])->name('ajax_search.action');

Step 7: Run the laravel dev server

You are done, to see the result, go to your project root directory and open cmd, then run the below command to see your records list.

php artisan serve

Then visit the below URL to delete multiple rows in laravel 10

http://localhost:8000/users-list

Thanks for reading. Aso read Laravel 10 Ajax Live Search!

Related Posts

Leave a Reply

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