Laravel Ajax Multiple Delete Records using Checkbox Example

Laravel 10, 9, 8 ajax multiple delete records using checkbox example. In this tutorial, you will learn how to how to delete multiple rows using checkbox in jQuery ajax laravel 10, 9, 8 app.

Sometimes you need delete multiple records from table and database with checkboxes using jQuery ajax in laravel app. So, You just need to follow some given steps to done of these delete multiple rows using checkbox in jQuery ajax laravel app.

How to delete multiple rows using checkbox in jQuery ajax laravel

Follow the below given steps and delete multiple rows with checkbox using ajax in PHP Laravel app:

  • Step 1 – Install Laravel App
  • Step 2 – Connecting App to Database
  • Step 3 – Create Model and Migration
  • Step 4 – Add Routes
  • Step 5 – Create Controllers By Artisan
  • Step 6 – Create Blade Views
  • Step 7 – Run Development Server
  • Step 8 – Test This App

Step 1 – Install Laravel App

First of all, Execute the following command on terminal to download or install laravel 8 fresh new setup:

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

Step 2 – Connecting App to Database

After that, open “.env” file and update the database name, username, and password in the env file:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=Enter_Your_Database_Name
DB_USERNAME=Enter_Your_Database_Username
DB_PASSWORD=Enter_Your_Database_Password

Step 3 – Create Modal and Migration

In this step, create category table migration and create category Modal by using the following command:

php artisan make:model Category -m

Navigate database/migrations/ and open create_categorys_table.php file. Then update the following code into this file:

    public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->id();
            $table->string('name');
            $table->text('description');
            $table->timestamps();
        });
    }

Now run the following command

php artisan migrate

Next, open Category.php model file and update the following code into it, which is placed on app/Models/:

<?php

namespace App\Models;

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

class Category extends Model
{
    protected $fillable = [
        'name',''description'
    ];
}

Step 4 – Add Routes

Next step, Navigate to “routes/web.php” file and add the following routes into your web.php file:

use App\Http\Controllers\CategoryController;

Route::get('cat', [CategoryController::class, 'index']);
Route::delete('category/{id}', [CategoryController::class, 'destroy']);
Route::delete('delete-multiple-category', [CategoryController::class, 'deleteMultiple']);

Step 5 – Create Controllers by Artisan

Next step, execute the following command on terminal to create controller file that named CategoryController:

php artisan make:controller CategoryController 

This command will create CategoryController by the artisan command.

Next, Navigate to app/http/controller and open CategoryController.php.Then update the following methods into your controller file:

<?php
namespace App\Http\Controllers;
use App\Models\Category;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Route;
class CategoryController extends Controller
{

    public function index(Request $request)
    {
        $data['categories'] = Category::get();
        return view('index', $data);
    }

    public function destroy(Request $request,$id)
    {
        $category=Category::find($id);
        $category->delete();
        return back()->with('success','Category deleted successfully');
    }

    public function deleteMultiple(Request $request)
    {
        $ids = $request->ids;
        Category::whereIn('id',explode(",",$ids))->delete();
        return response()->json(['status'=>true,'message'=>"Category deleted successfully."]);

    }

}

Step 6 – Create Blade Views

In this step, create one blade views file for rendering data on it. So navigate to resources/views folder and create the blade view as following:

Create first file name index.blade.php and update the following code into it:

<!DOCTYPE html>
<html>
<head>
    <title>Laravel - how to delete multiple rows in mysql using checkbox</title>


    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

   <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous">

  <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script>
>
    <meta name="csrf-token" content="{{ csrf_token() }}">

</head>
<body>


<div class="container">
    <h3>PHP delete multiple records by selecting checkboxes using javascript</h3>
    @if ($message = Session::get('success'))
    <div class="alert alert-success">
        <p>{{ $message }}</p>
    </div>
    @endif
    <button style="margin: 5px;" class="btn btn-danger btn-xs delete-all" data-url="">Delete All</button>
    <table class="table table-bordered">
        <tr>
            <th><input type="checkbox" id="check_all"></th>
            <th>S.No.</th>
            <th>Category Name</th>
            <th>Category Details</th>
            <th width="100px">Action</th>
        </tr>
        @if($categories->count())
            @foreach($categories as $key => $category)
                <tr id="tr_{{$category->id}}">
                    <td><input type="checkbox" class="checkbox" data-id="{{$category->id}}"></td>
                    <td>{{ ++$key }}</td>
                    <td>{{ $category->name }}</td>
                    <td>{{ $category->description }}</td>
                    <td>
                        {!! Form::open(['method' => 'DELETE','route' => ['category.destroy', $category->id],'style'=>'display:inline']) !!}

                            {!! Form::button('Delete', ['class' => 'btn btn-danger btn-xs','data-toggle'=>'confirmation','data-placement'=>'left']) !!}

                        {!! Form::close() !!}
                    </td>
                </tr>
            @endforeach
        @endif
    </table>
</div>

</body>

<script type="text/javascript">
    $(document).ready(function () {

        $('#check_all').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){
                $('#check_all').prop('checked',true);
            }else{
                $('#check_all').prop('checked',false);
            }
         });

        $('.delete-all').on('click', function(e) {


            var idsArr = [];
            $(".checkbox:checked").each(function() {
                idsArr.push($(this).attr('data-id'));
            });


            if(idsArr.length <=0)
            {
                alert("Please select atleast one record to delete.");
            }  else {

                if(confirm("Are you sure, you want to delete the selected categories?")){

                    var strIds = idsArr.join(",");

                    $.ajax({
                        url: "{{ route('category.multiple-delete') }}",
                        type: 'DELETE',
                        headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                        data: 'ids='+strIds,
                        success: function (data) {
                            if (data['status']==true) {
                                $(".checkbox:checked").each(function() {
                                    $(this).parents("tr").remove();
                                });
                                alert(data['message']);
                            } else {
                                alert('Whoops Something went wrong!!');
                            }
                        },
                        error: function (data) {
                            alert(data.responseText);
                        }
                    });


                }
            }
        });

        $('[data-toggle=confirmation]').confirmation({
            rootSelector: '[data-toggle=confirmation]',
            onConfirm: function (event, element) {
                element.closest('form').submit();
            }
        });

    });
</script>


</html>

Step 7 – Run Development Server

In this step, use the following php artisan serve command to start your server locally:

php artisan serve

Step 8 – Test This App

Now, open browser and hit the following url on it for test this app:

http://localhost:8000/cat

Conclusion

Laravel 8 ajax multiple delete records using checkbox example. In this tutorial, you have learned how to how to delete multiple rows using checkbox in jQuery ajax laravel 8 app.

Recommended Laravel Posts

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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