article

Thursday, July 6, 2023

Laravel 10 Delete Multiple Data using Checkbox | Jquery Ajax

Laravel 10 Delete Multiple Data using Checkbox | Jquery Ajax

Download Laravel App

composer create-project --prefer-dist laravel/laravel my-app
C:\xampp\htdocs\laravel10project>composer create-project laravel/laravel laravel10project

Connecting our Database

open .env file root directory.

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

Database Migration
php artisan migrate

C:\xampp\htdocs\laravel\laravel10project>php artisan migrate

Migration table created successfully.

check database table

user data 
C:\xampp\htdocs\laravel\laravel10project>php artisan tinker
User::factory()->count(100)->create()

Create Controller
php artisan make:controller UserController
C:\xampp\htdocs\laravel\my-app>php artisan make:controller UserController

app/Http/Controllers/UserController.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//app/Http/Controllers/UserController.php
<?php
 
namespace App\Http\Controllers;
 
use Illuminate\Http\Request;
use App\Models\User;
 
class UserController extends Controller
{
    public function index(Request $request)
    {
        $data['users'] = User::get();
        return view('home', $data);
    }
  
    public function removeMulti(Request $request)
    {
        $ids = $request->ids;
        User::whereIn('id',explode(",",$ids))->delete();
        return response()->json(['status'=>true,'message'=>"User successfully removed."]);
          
    }
}
View Blade
Bootstrap 5
https://getbootstrap.com/docs/5.0/getting-started/introduction/
https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css

Jquery
https://jquery.com/download/
CDN : jsDelivr CDN
https://www.jsdelivr.com/package/npm/jquery

resources/views/home.blade.php
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
//resources/views/home.blade.php
<!DOCTYPE html>
<html lang="{{ str_replace('_', '-', app()->getLocale()) }}">
<head>
    <title>Laravel 10 Delete Multiple Data using Checkbox | Jquery Ajax</title>
    <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 10 Delete Multiple Data using Checkbox | Jquery Ajax</h2>
         <button class="btn btn-primary btn-xs removeAll mb-3">Remove All Selected Data</button>
         <table class="table table-bordered">
            <tr>
               <th><input type="checkbox" id="checkboxesMain"></th>
               <th>Id</th>
               <th>Name</th>
               <th>Email</th>
            </tr>
            @if($users->count())
            @foreach($users as $key => $rs)
            <tr id="tr_{{$rs->id}}">
               <td><input type="checkbox" class="checkbox" data-id="{{$rs->id}}"></td>
               <td>{{ ++$key }}</td>
               <td>{{ $rs->name }}</td>
               <td>{{ $rs->email }}</td>
            </tr>
            @endforeach
            @endif
         </table>
      </div>
<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 userIdArr = [];
            $(".checkbox:checked").each(function() {
                userIdArr.push($(this).attr('data-id'));
            });
            if (userIdArr.length <= 0) {
                alert("Choose min one item to remove.");
            } else {
                if (confirm("Are you sure you want to delete")) {
                    var stuId = userIdArr.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>
</body>
</html>
Routes
routes/web.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
//routes/web.php
<?php
 
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\UserController;
 
/*
|--------------------------------------------------------------------------
| 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', [UserController::class, 'index']);
Route::delete('delete-all', [UserController::class, 'removeMulti']);
Run C:\xampp\htdocs\laravel\my-app>php artisan serve
Starting Laravel development server: http://127.0.0.1:8000

Related Post