In this tutorial you will learn about the Laravel Ajax Multiple Delete Records using Checkbox Example and its application with practical example.
In this Laravel Ajax Multiple Delete Records using Checkbox Example tutorial I will show you how to select multiple records using checkbox and delete using ajax in laravel application. In this tutorial you will learn to select multiple records using checkbox and delete records using ajax in laravel application. In this article I will share example to select and delete multiple record from table using checkbox in laravel. We will be using jquery ajax to select and delete multiple records using checkbox in laravel.
Laravel Ajax Multiple Delete Records using Checkbox Example
In this step by step tutorial I will demonstrate you with example on how to select and delete multiple record from table using checkbox in laravel. Please follow the instruction given below:
- Step 1 – Install Laravel 8 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 8 App
First of all we need to create a fresh laravel project, download and install Laravel 8 using the below command
1 |
composer create-project --prefer-dist laravel/laravel blog |
Step 2 – Connecting App to Database
Now, lets create a MySQL database and connect it with laravel application. After creating database we need to set database credential in application’s .env file.
1 2 3 4 5 6 |
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
Now, in this step we will create model and migration file. Please run the following command:
1 |
php artisan make:model Category -m |
Now, go to database/migrations/ and open create_categorys_table.php file. Then update the following code into this file:
1 2 3 4 5 6 7 8 9 |
public function up() { Schema::create('categories', function (Blueprint $table) { $table->id(); $table->string('name'); $table->text('description'); $table->timestamps(); }); } |
Now, run the migration to create database table using following artisan command:
1 |
php artisan migrate |
Next, open Category.php model file and update the following code into it, which is placed on app/Models/:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
<?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
After this, we need to define routes in “routes/web.php” file. Lets open “routes/web.php” file and add the following routes in it.
routes/web.php
1 2 3 4 5 |
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
Now, lets create a controller named CategoryController using command given below –
1 |
php artisan make:controller CategoryController |
The above command will create CategoryController. Now, go to app/http/controller and open CategoryController.php.Then put the following methods into your controller file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
<?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 we will create blade views file for rendering data on it. So go 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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 |
<!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/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/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>Laravel 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
Now we are ready to run our example so lets start the development server using following artisan command –
1 |
php artisan serve |
Now, open the following URL in browser to see the output –
1 |
http://localhost:8000/cat |