Laravel-9 Tutorial – How to Delete Multiple Data using Checkbox in Laravel 9

A checkbox is a handy GUI element. It allows users to select multiple options among given options in a list.

A checkbox is a profound UI component; you can use it to select or deselect action items. In this tutorial, you will find out how to remove multiple SQL records with a checkbox in Laravel using AJAX.

Data is laid in rows and columns format in a database. Every row contains information, and every piece of information reckon as data. The primary job of a developer is to add, update or remove data from the database.

Specific tools help communicate with the server. We will use AJAX to delete rows from the database using the checkbox in Laravel. Lets us throw some light on

AJAX stands for Asynchronous JavaScript And XML. It is a set of striking web development techniques that uses various web technologies on the client side to build asynchronous web applications.

It makes web developers’ lives less cumbersome by helping send and retrieve data from a server asynchronously without reloading the web page.

How to Delete SQL Data Rows with Checkbox using Ajax in Laravel 9

  • Step 1: Create Laravel Project
  • Step 2: Build Database Connection
  • Step 3: Generate New Model
  • Step 4: Rub Database Migration
  • Step 5: Create New Controller
  • Step 6: Build View File
  • Step 7: Set Up New Routes
  • Step 8: Run Laravel Server

Create Laravel Project

In the initial step, you must run the command to create a new Laravel application. You should install Composer and must have a code editor with a cli tool.

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

Use command to step inside the project.

cd laravel-demo

Build Database Connection

To connect laravel with the database; you require to add database details inside the .env config file.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=database_username
DB_PASSWORD=database_password

For macOS MAMP server; ensure that you add UNIX_SOCKET and DB_SOCKET below database details in .env file.

UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock

Generate New Model

A modal file holds the modal class; the modal class contains a set of data that is directly related to data points.

php artisan make:model Student -m

A new modal file has been created; furthermore, you have to move into the app/Models/ folder here; you will see the Student.php file; you have to add the given code there.


namespace AppModels;
use IlluminateDatabaseEloquentFactoriesHasFactory;
use IlluminateDatabaseEloquentModel;
class Student extends Model
{
    use HasFactory;
    protected $fillable = [
        'subject',
        'details'
    ];    
}

Setting Up Migrations

In the previous step we generated a new model and added the new values to the model. This time we will send those values into the database table.

Head over to database/migrations/xxxx_create_students_table.php file and insert the given code into the file.


use IlluminateDatabaseMigrationsMigration;
use IlluminateDatabaseSchemaBlueprint;
use IlluminateSupportFacadesSchema;
return new class extends Migration
{
    
    public function up()
    {
        Schema::create('students', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->string('details');
            $table->timestamps();
        });
    }
    
    public function down()
    {
        Schema::dropIfExists('students');
    }
};

Go ahead and run the given command.

php artisan migrate

Create New Controller

The CLI tool utterly reduces the pain of creating imperative files. We can use the composer command to generate a new controller.

php artisan make:controller StudentController

You have to create the functions which will handle the records deletion in contrast to SQL database.

Open the app/Http/Controllers/StudentController.php and add the given code to the file.


namespace AppHttpControllers;
use AppModelsStudent;
use IlluminateHttpRequest;
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 successfully removed."]);
         
    }
 
}

Build View File

To setup a view relative to the controller; you must create a home.blade.php file in resources/views directory.

Make sure to place the given code into the file.

<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
   <head>
      <title>Laravel Multi Checkboxes 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 Delete Example</h2>
         <button class="btn btn-primary btn-xs removeAll mb-3">Remove All Data</button>
         <table class="table table-bordered">
            <tr>
               <th><input type="checkbox" id="checkboxesMain"></th>
               <th>Id</th>
               <th>Category Name</th>
               <th>Category Details</th>
            </tr>
            @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
         </table>
      </div>
      <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

   </body>
   <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("Choose min one item to remove.");
            } else {
                if (confirm("Are you sure?")) {
                    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).parents("tr").remove();
                                });
                                alert(data['message']);
                            } else {
                                alert('Error occured.');
                            }
                        },
                        error: function(data) {
                            alert(data.responseText);
                        }
                    });
                }
            }
        });
    }); 
 </script>
</html>

Set Up New Routes

We need to create the route URLs; these links will invoke the request from the view file to the controller.

Hence, open the routes/web.php file and insert the given code into the file.


use IlluminateSupportFacadesRoute;
use AppHttpControllersStudentController;

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

Run Laravel Server

In the last step, you have to run the laravel application. Running a laravel app is simple; all it takes is a single class that can fire up the laravel server.

php artisan serve

You can add this url to your browser’s address bar to test the app.

http://127.0.0.1:8000/students

How to Delete Multiple Data using Checkbox in Laravel 9

Conclusion

A checkbox is a graphical widget that enables the user to make a binary choice.

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 9 application.

Leave a Reply

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