How to Delete Multiple Data using Checkbox in Laravel 11

Checkboxes are essential UI components that enable users to either select or deselect items based on their preferences. In this Laravel multiple data remove with checkbox example, you learned how to use AJAX to delete multiple records from the SQL database using the checkbox in Laravel application.

Step 1 – Create a New Laravel App

Start by creating a fresh Laravel project using Composer. Ensure you have Composer installed and a code editor with a CLI tool.

composer create-project laravel/laravel --prefer-dist laravel-app

Navigate into your newly created project directory:

cd laravel-app

Step 2 – Configure Database Connection

To connect Laravel to your database, you need to add your database credentials to the .env file. Open the .env file and update the database configuration:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_username
DB_PASSWORD=your_database_password

Step 3 – Generate a Model

Create a model and migration file for the Student entity using Artisan:

php artisan make:model Student -m

A new model file will be created. Navigate to app/Models/Student.php and update it with the following code:

<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Student extends Model
{
use HasFactory;

protected $fillable = [
'name',
'details'
];
}

Step 4 – Set Up Migrations

Update the migration file located in database/migrations/xxxx_create_students_table.php with the following code to define the structure of the students table:

<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('students', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('details');
$table->timestamps();
});
}

/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('students');
}
};

Run the migration to create the table:

php artisan migrate

Step 5 – Create a Controller

Generate a new controller using Artisan:

php artisan make:controller StudentController

Open app/Http/Controllers/StudentController.php and add the following methods:

<?php

namespace App\Http\Controllers;

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

class StudentController extends Controller
{
public function index(Request $request)
{
$data['students'] = Student::get();
return view('home', $data);
}

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

Step 6 – Build the View File

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

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
<title>Laravel Multiple Checkbox Example</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-GLhlTQ8iRABdZLl6O3oVMWSktQOp6b7In1Zl3/Jr59b6EGGoI1aFkw7cmDA6j6gD" crossorigin="anonymous">
<meta name="csrf-token" content="{{ csrf_token() }}">
</head>
<body>
<div class="container">
@if ($message = Session::get('success'))
<div class="alert alert-info">
<p>{{ $message }}</p>
</div>
@endif

<h2 class="mb-4">Laravel Checkbox Multiple Rows Deletion Example</h2>
<button class="btn btn-primary btn-xs removeAll mb-3">Remove Selected</button>
<table class="table table-bordered">
<thead>
<tr>
<th><input type="checkbox" id="checkboxesMain"></th>
<th>ID</th>
<th>Name</th>
<th>Details</th>
</tr>
</thead>
<tbody>
@if($students->count())
@foreach($students as $key => $student)
<tr id="tr_{{$student->id}}">
<td><input type="checkbox" class="checkbox" data-id="{{$student->id}}"></td>
<td>{{ ++$key }}</td>
<td>{{ $student->name }}</td>
<td>{{ $student->details }}</td>
</tr>
@endforeach
@endif
</tbody>
</table>
</div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">
$(document).ready(function() {
$('#checkboxesMain').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) {
$('#checkboxesMain').prop('checked', true);
} else {
$('#checkboxesMain').prop('checked', false);
}
});

$('.removeAll').on('click', function(e) {
var studentIdArr = [];
$(".checkbox:checked").each(function() {
studentIdArr.push($(this).attr('data-id'));
});

if (studentIdArr.length <= 0) {
alert("Please select at least one item to remove.");
} else {
if (confirm("Are you sure you want to delete the selected records?")) {
var stuId = studentIdArr.join(",");
$.ajax({
url: "{{url('delete-all')}}",
type: 'DELETE',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: { 'ids': stuId },
success: function(data) {
if (data['status'] == true) {
$(".checkbox:checked").each(function() {
$(this).closest("tr").remove();
});
alert(data['message']);
} else {
alert('An error occurred.');
}
},
error: function(data) {
alert(data.responseText);
}
});
}
}
});
});
</script>
</body>
</html>

Step 7 – Set Up Routes

Define the routes for your application by editing the routes/web.php file:

<?php

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

Route::get('students', [StudentController::class, 'index']);
Route::delete('delete-all', [StudentController::class, 'removeMulti']);

Step 8 – Run the Laravel Application

Finally, start the Laravel development server with:

php artisan serve

Access the application by navigating to the following URL in your web browser:

http://127.0.0.1:8000/students

d