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

تحديث حالة status (مفعل، غير مفعل)، بإستخدام Toggles Switchery مع رسالة Toaster

تحديث حالة status (مفعل، غير مفعل)، بإستخدام Toggles Switchery مع رسالة Toaster

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

جدول المحتويات



نحاول دائما كمبرمجين تقديم أفضل أنطباع وأريحية للعملاء في التعامل مع التطبيق، في هذه المقالة القصيره سيتم التطرق لكيفية تحديث حقل status بإستخدام مكتبة Switchery ، وإظهار رسالة للعميل تفيد أنه تم التحديث بإستخدام مكتبة Toastr.

فما نحاول الحصول علية كما في الصورة


جلب البيانات من جدول authors

public function index()
{
    $authors=Author::select('id','fname','email','status','created_at')->get();
    return view('author',compact('authors'));
}


عرض البيانات في ملف blade

@foreach($authors as $author)
    <tr>
        <th scope="row">{{ $author->id }}</th>
        <td>{{ $author->fname }}</td>
        <td>{{ $author->email }}</td>
        <td>{{ $author->status }}</td>
        <td>{{ $author->created_at->diffForHumans() }}</td>
    </tr>
@endforeach


بالتالي سوف نحصل على هذه النتيجة


إضافة مكتبة Switchery Toggle Buttons

كما نرى بالصوره أعلاه أن قيمة status إما 2 أو 1، وعليها سوف يتم تطبيق الشكل الخاص بالمكتبة

تضمين ملف css

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/switchery/0.8.2/switchery.min.css">

تضمين مكتبة jquery

<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/switchery/0.8.2/switchery.min.js"></script>

إعدادات المكتبة

<script>
let elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
elems.forEach(function(html) {
    let switchery = new Switchery(html,  { size: 'small' });
});
</script>


الأن يمكننا تطبيق المكتبة على حقل status

<td><input type="checkbox" data-id="{{ $author->id }}" name="status" class="js-switch" {{ $author->status == 1 ? 'checked' : '' }}></td>


الأن سوف نحصل على هذا الشكل




لكن كيف يمكن تعديل قيمة الحقل في قاعدة البيانات عند الضغط على switcher؟

للقيام بذلك سوف يتم إستخدام مكتبة ajax لإرسال الحالة مع author_id، والتي نحصل عليها من data-id attribute .

$(document).ready(function(){
    $('.js-switch').change(function () {
        let status = $(this).prop('checked') === true ? 1 : 2;
        let authorId = $(this).data('id');
        $.ajax({
            type: "GET",
            dataType: "json",
            url: '{{ route('author.update.status') }}',
            data: {'status': status, 'author_id': authorId },
            success: function (data) {
                console.log(data.message);
            }
        });
    });
});


في كود ajax فإننا نستهدف أي عنصر html يأخذ كلاس js-switch ، وفي حالة تغيير الحالة change فإننا نحصل على الحالة من خلال prop (2,1)، وفي المتغير authorId قمنا بالحصول على id المؤلف.


إضافة route في ملف web.php

Route::get('/status/update', [AuthorController::class, 'updateStatus'])->name('author.update.status');



إنشاء دالة تعديل الحالة بداخل controller

public function updateStatus(Request $request)
{
    $author = Author::findOrFail($request->author_id);
    $author->status = $request->status;
    $author->save();

    return response()->json(['message' => 'User status updated successfully.']);
}


الأن يجب أن يعمل الكود بشكل سليم ويمكننا تغيير الحالة بنجاح.


إضافة مكتبة Toaster للإشعارات

سنستخدم المكتبة حتى يظهر إشعار للمستخدم أنه تم تعديل الحالة بنجاح

إضافة مكتبة css

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


إضافة مكتبة js

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



ولتطبيق مكتبة toaster بداخل الدالة success في طلب ajax يتم إضافة الكود الخاص بالمكتبة

success: function (data) {
    toastr.options.closeButton = true;
    toastr.options.closeMethod = 'fadeOut';
    toastr.options.closeDuration = 100;
    toastr.success(data.message);
}


كود عرض الصفحة بالكامل

<html>
<head>
    <title></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/switchery/0.8.2/switchery.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.css">


</head>
<body>
<div class="container">
    <div class="card">
        <h5 class="card-header">Authors</h5>
        <div class="card-body">
            <table class="table table-bordered table-striped">
                <thead>
                <tr>
                    <th scope="col">#</th>
                    <th scope="col">Name</th>
                    <th scope="col">Email</th>
                    <th scope="col">Status</th>
                    <th scope="col">Created_at</th>
                </tr>
                </thead>
                <tbody>
                @foreach($authors as $author)
                    <tr>
                        <th scope="row">{{ $author->id }}</th>
                        <td>{{ $author->fname }}</td>
                        <td>{{ $author->email }}</td>
                        <td><input type="checkbox" data-id="{{ $author->id }}" name="status" class="js-switch" {{ $author->status == 1 ? 'checked' : '' }}></td>
                        <td>{{ $author->created_at->diffForHumans() }}</td>
                    </tr>
                @endforeach
                </tbody>
            </table>
        </div>
    </div>
</div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/switchery/0.8.2/switchery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/toastr.js/latest/toastr.min.js"></script>

<script>
    let elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch'));
    elems.forEach(function(html) {
        let switchery = new Switchery(html,  { size: 'small' });
    });


    $(document).ready(function(){
        $('.js-switch').change(function () {
            let status = $(this).prop('checked') === true ? 1 : 2;
            let authorId = $(this).data('id');
            $.ajax({
                type: "GET",
                dataType: "json",
                url: '{{ route('author.update.status') }}',
                data: {'status': status, 'author_id': authorId },
                success: function (data) {
                    toastr.options.closeButton = true;
                    toastr.options.closeMethod = 'fadeOut';
                    toastr.options.closeDuration = 100;
                    toastr.success(data.message);
                }
            });
        });
    });
</script>
</body>
</html>

التعليقات
زائر
منذ 3 سنوات

عااشت ايدك درس راقي مثلك ياراقي

زائر
منذ 3 سنوات

ممتاز بارك الله فيك استمر من فضلك

tohami
منذ سنة

جميل جدا عاش نضال الشعب الفلسطيني

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