لارافيل, JQuery / 2024-05-15

الحذف المتعدد بإستخدام laravel مع ajax بإستخدام checkbox

الحذف المتعدد بإستخدام laravel مع ajax بإستخدام checkbox

2024-05-15 وقت القراءه : 6 دقائق

تحسين تجربة المستخدم تعد واحده من أهم الإمور التي يجب الإهتمام بها أثناء العمل على التطبيقات، وواحده من الإمور التي تساهم في تحسين تجربه المستخدم هي إتاحة الحذف المتعدد، في هذه المقالة سيتم شرح كيفية القيام بذلك بإستخدام إطار العمل لارافيل.

الخطوات

جلب البيانات

public function index(){
    $users=User::select('id','name')->get();
    return view('/users',compact('users'));
}

عرض البيانات

<table class="table table-bordered table-striped table-hover">
    <tr class="table-dark">
        <td><input type="checkbox" id="check_all"></td>
        <td>Id</td>
        <td>Name</td>
    </tr>
    @foreach($users as $user)
        <tr>
            <td><input type="checkbox" class="checkbox" data-id="{{$user->id}}"></td>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
        </tr>
    @endforeach
    <tr>
        <td colspan="3"><button class="btn btn-danger delete-all">Delete All</button> </td>
    </tr>
</table>

كما نلاحظ في جدول عرض البيانات إنه تم إضافة 2 checkbox.

  • الأول وتم إعطاءه id=check_all وسيتم إستخدامه لتحديد جميع checkbox عند الضغط علية.
  • الثاني وتم إعطاءه class=checkbox وكذلك data-id=$user_id وذلك حتى يتم تخزين id العنصر المراد حذفه اذا كان قد تم إختياره.


تضمين مكتبة جافا سكربت ومكتبة toast في ملف blade

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">

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


كتابة كود ajax

<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('delete-multiple-category') }}",
                        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();//حذف الصف بعد اتمام الحذف من قاعدة البيانات
                                });
//رسالة toast للحذف
                                toastr.options.closeButton = true;
                                toastr.options.closeMethod = 'fadeOut';
                                toastr.options.closeDuration = 100;
                                toastr.success('Deleted Successfully');
                            } else {
                                alert('Whoops Something went wrong!!');
                            }
                        },
                        error: function (data) {
                            alert(data.responseText);
                        }
                    });
                }
            }
        });
    });
</script>

بعد الحذف سيتم إظهار رسالة toast وكذلك سيتم حذف الصف من ملف blade بإستخدام jquery.


إضافة csrf_token

في ملف العرض إضافة csrf-token في الهيدر

<meta name="csrf-token" content="{{ csrf_token() }}">


إنشاء route

Route::get('/users',[UserController::class,'index']);
Route::delete('delete-multiple-category', [UserController::class, 'deleteMultiple'])->name('delete-multiple-category');


دالة الحذف بداخل UserController

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


الكود بالكامل مع رسالة toast

<!doctype html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">
    <title>Users</title>
</head>
<body>
<table class="table table-bordered table-striped table-hover">
    <tr class="table-dark">
        <td><input type="checkbox" id="check_all"></td>
        <td>Id</td>
        <td>Name</td>
    </tr>
    @foreach($users as $user)
        <tr>
            <td><input type="checkbox" class="checkbox" data-id="{{$user->id}}"></td>
            <td>{{ $user->id }}</td>
            <td>{{ $user->name }}</td>
        </tr>
    @endforeach
    <tr>
        <td colspan="3"><button class="btn btn-danger delete-all">Delete All</button> </td>
    </tr>
</table>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js"></script>
<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('delete-multiple-category') }}",
                        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();
                                });
                                toastr.options.closeButton = true;
                                toastr.options.closeMethod = 'fadeOut';
                                toastr.options.closeDuration = 100;
                                toastr.success('Deleted Successfully');
                            } else {
                                alert('Whoops Something went wrong!!');
                            }
                        },
                        error: function (data) {
                            alert(data.responseText);
                        }
                    });
                }
            }
        });
    });
</script>
</body>
</html>




التعليقات
Abdulrahman Masoud
منذ سنتين

ربنا يزيدك من علمه ويرزقك الخير وينفع بيك يارب

إضافة تعليق
Loading...