Membuat Multiple Delete dengan checkbox menggunakan Laravel 5
Jurnalcode.com

Membuat Multiple Delete dengan checkbox menggunakan Laravel 5

Membuat Multiple Delete dengan checkbox menggunakan Laravel 5


Jurnalcode : Kali ini saya akan membagikan tutorial bagaimana menghapus multiple  data/ record pada database dengan checkbox di laravel 5 . teknik ini sangat menguntungkan karena dapat menghemat waktu untuk menghapus record dibadingkan dengan delete data manual one by one.  nah sekarang saya akan menerapkan nya menggunakan frameword laravel yang mana frmaework ini sedang booming dan diminati banyak programmer dunia.

oke langsung saja kita ke pokok permasalahan nya .

Langkah pertama

Silahkan Buat Database terlebih dahulu , contoh :

INSERT INTO `products` (`id`, `name`, `details`, `created_at`, `updated_at`) VALUES
(1, 'Laravel', 'Laravel posts', NULL, NULL),
(3, 'PHP', 'PHP posts', NULL, NULL),
(4, 'JQuery', 'JQuery posts', NULL, NULL),
(5, 'Bootstrap', 'Bootstrap posts', NULL, NULL),
(6, 'Ajax', 'Ajax posts', NULL, NULL);

 Langkah Kedua

Silahkan Install Laravel kesayangan kalian :), dan stelah selesai installasi silahkan ke folder Routes/web.php dan tambahkan script route berikut :

Route::get('myproducts', '[email protected]');
Route::delete('myproducts/{id}', '[email protected]');
Route::delete('myproductsDeleteAll', '[email protected]');

 

Langkah Ketiga :

Dilanjutkan lagi dengan membuat sebuah controller , silahkan kalian menuju ke arah app/Http/Controllers/ dan buat controller dengan nama ProductController.php . controller ini dapat dibuat melalui composer.

<?php
namespace AppHttpControllers;
use IlluminateHttpRequest;
use DB;

class ProductController extends Controller
{
    public function index()
    {
        $products = DB::table("products")->get();
        return view('products',compact('products'));
    }

    public function destroy($id)
    {
    	DB::table("products")->delete($id);
    	return response()->json(['success'=>"Product Deleted successfully.", 'tr'=>'tr_'.$id]);
    }
   
    public function deleteAll(Request $request)
    {
        $ids = $request->ids;
        DB::table("products")->whereIn('id',explode(",",$ids))->delete();
        return response()->json(['success'=>"Products Deleted successfully."]);
    }
}

 

Langkah Terakhir

Langkah Terakhir adalah membuat View nya silahkan kalian menuju ke folder Resources/views/ dan buat file view dengan nama products.blade.php

 

<!DOCTYPE html>
<html>
<head>
    <title>Multiple delete Laravel</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.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/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-confirmation/1.0.5/bootstrap-confirmation.min.js"></script>

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

</head>

<body>
<div class="container">
    <h3>Multiple delete Laravel Jurnalcode</h3>
    <button style="margin-bottom: 10px" class="btn btn-primary delete_all" data-url="{{ url('myproductsDeleteAll') }}">Delete All Selected</button>
    <table class="table table-bordered">
        <tr>
            <th width="50px"><input type="checkbox" id="master"></th>
            <th width="80px">No</th>
            <th>Product Name</th>
            <th>Product Details</th>
            <th width="100px">Action</th>
        </tr>

        @if($products->count())
            @foreach($products as $key => $product)
                <tr id="tr_{{$product->id}}">
                    <td><input type="checkbox" class="sub_chk" data-id="{{$product->id}}"></td>
                    <td>{{ ++$key }}</td>
                    <td>{{ $product->name }}</td>
                    <td>{{ $product->details }}</td>
                    <td>
                         <a href="{{ url('myproducts',$product->id) }}" class="btn btn-danger btn-sm"
                           data-tr="tr_{{$product->id}}"
                           data-toggle="confirmation"
                           data-btn-ok-label="Delete" data-btn-ok-icon="fa fa-remove"
                           data-btn-ok-class="btn btn-sm btn-danger"
                           data-btn-cancel-label="Cancel"
                           data-btn-cancel-icon="fa fa-chevron-circle-left"
                           data-btn-cancel-class="btn btn-sm btn-default"
                           data-title="Are you sure you want to delete ?"
                           data-placement="left" data-singleton="true">
                            Delete
                        </a>
                    </td>
                </tr>
            @endforeach
        @endif
    </table>
</div>
</body>

<script type="text/javascript">
    $(document).ready(function () {
        $('#master').on('click', function(e) {
         if($(this).is(':checked',true))  
         {
            $(".sub_chk").prop('checked', true); 
         } else {  
            $(".sub_chk").prop('checked',false); 
         }  
        });

        $('.delete_all').on('click', function(e) {
            var allVals = [];  
            $(".sub_chk:checked").each(function() {  
                allVals.push($(this).attr('data-id'));
            });  

            if(allVals.length <=0)  
            {  
                alert("Please select row."); 
            }  else {  
                var check = confirm("Are you sure you want to delete this row?"); 
                if(check == true){  
                    var join_selected_values = allVals.join(","); 

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

                  $.each(allVals, function( index, value ) {
                      $('table tr').filter("[data-row-id='" + value + "']").remove();
                  });
                } 
            }  
        });

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

        $(document).on('confirm', function (e) {
            var ele = e.target;
            e.preventDefault();

            $.ajax({
                url: ele.href,
                type: 'DELETE',
                headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')},
                success: function (data) {
                    if (data['success']) {
                        $("#" + data['tr']).slideUp("slow");
                        alert(data['success']);
                    } else if (data['error']) {
                        alert(data['error']);
                    } else {
                        alert('Whoops Something went wrong!!');
                    }
                },
                error: function (data) {
                    alert(data.responseText);
                }
            });
            return false;
        });
    });
</script>
</html>

  Sekian tutorial dari saya semoga bermanfaat . terimakasih salam coder

.

Ayo Komentar