Lara_Love's avatar

Delete multi item

i want delete many product but it have not error not working . where is error ?

Route::delete('myproductsDeleteAll', 'ProductController@deleteAll');

Controller

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

route and view

<button 
          data-url="{{ url('myproductsDeleteAll') }}">
          Delete All 
</button>

@if($items->count())
            @foreach($items as $key => $item)
                <tr>
                    <td><input type="checkbox" class="sub_chk" data-id="{{$item->id}}"></td>

                    <td>{{ ++$key }}</td>

{{ $item->name }}


and

<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>
0 likes
17 replies
christian-qode's avatar

@lovercode Have you dumped $request yet? I think $request->ids should be replaced by $request->get('ids');

Besides that, because it's a DELETE sql command, I'ld highly recommend you to add additional validation.

1 like
Sergiu17's avatar

first of all, make sure that the php receives those ids

public function deleteAll(Request $request)
{
	dd($request->ids);

if not, the problem is in JS,

var join_selected_values = allVals.join(",");
console.log(join_selected_values);

if ids are correct, see how you send data to the server

1 like
Lara_Love's avatar

after i click delete show in window https://postimg.cc/jDZNnpd8 and it dosen't work

{
    "message": "",
    "exception": "Symfony\Component\HttpKernel\Exception\NotFoundHttpException",
    "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Routing\AbstractRouteCollection.php",
    "line": 44,
    "trace": [
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Routing\CompiledRouteCollection.php",
            "line": 144,
            "function": "handleMatchedRoute",
            "class": "Illuminate\Routing\AbstractRouteCollection",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
            "line": 680,
            "function": "match",
            "class": "Illuminate\Routing\CompiledRouteCollection",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
            "line": 667,
            "function": "findRoute",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Routing\Router.php",
            "line": 656,
            "function": "dispatchToRoute",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
            "line": 190,
            "function": "dispatch",
            "class": "Illuminate\Routing\Router",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
            "line": 141,
            "function": "Illuminate\Foundation\Http\{closure}",
            "class": "Illuminate\Foundation\Http\Kernel",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
            "line": 21,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull.php",
            "line": 31,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
            "line": 180,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TransformsRequest.php",
            "line": 21,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\TrimStrings.php",
            "line": 40,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\TransformsRequest",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
            "line": 180,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\TrimStrings",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\ValidatePostSize.php",
            "line": 27,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
            "line": 180,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\ValidatePostSize",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance.php",
            "line": 86,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
            "line": 180,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Middleware\PreventRequestsDuringMaintenance",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Http\Middleware\HandleCors.php",
            "line": 49,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
            "line": 180,
            "function": "handle",
            "class": "Illuminate\Http\Middleware\HandleCors",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Http\Middleware\TrustProxies.php",
            "line": 39,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
            "line": 180,
            "function": "handle",
            "class": "Illuminate\Http\Middleware\TrustProxies",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Pipeline\Pipeline.php",
            "line": 116,
            "function": "Illuminate\Pipeline\{closure}",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
            "line": 165,
            "function": "then",
            "class": "Illuminate\Pipeline\Pipeline",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\Http\Kernel.php",
            "line": 134,
            "function": "sendRequestThroughRouter",
            "class": "Illuminate\Foundation\Http\Kernel",
            "type": "->"
        },
        {
            "file": "G:\test\shop\public\index.php",
            "line": 52,
            "function": "handle",
            "class": "Illuminate\Foundation\Http\Kernel",
            "type": "->"
        },
        {
            "file": "G:\test\shop\vendor\laravel\framework\src\Illuminate\Foundation\resources\server.php",
            "line": 16,
            "function": "require_once"
        }
    ]
}
Lara_Love's avatar

@christian-qode

Route::delete('myproductsDeleteAll', [ProductController::class, 'deleteAll'])->name('myproductsDeleteAll');

but not working and show window

jaseofspades88's avatar

@LoverCode url('myproductsDeleteAll') won't get the route by name. Try using route('myproductsDeleteAll') and that should get the correct url for your 'form'.

Lara_Love's avatar

@jaseofspades88 i change to

web.php

Route::delete('myproductsDeleteAll', [ProductController::class, 'deleteAll'])->name('myproductsDeleteAll');


Form
<form action="{{ route('myproductsDeleteAll') }}" method="POST" >
                    @csrf
                    @method('DELETE')
                    <button type="submit"  class="btn btn-primary delete_all">
                        Delete All Selected
                    </button>
                </form>


Controller

public function deleteAll(Request $request)

    {
        $ids = $request->get('ids');
//        $ids = $request->ids;
        DB::table("products")->whereIn('id',explode(",",$ids))->delete();
        return redirect()->back()->with('success','OK');
    }

it return success bot not working

dd return :

null // app\Http\Controllers\ProductController.php:211

christian-qode's avatar

@LoverCode Am I correct you don't use the Javascript from the topic opening anymore? Now you're performing a request straight from the , but the form doesn't have an (hidden) input for ID's. You should either add the ID's to the form, or use Javascript to submit the forms with the ID's.

Lara_Love's avatar

@christian-qode i add column ids

$table->string('ids')->default('0');

in database and in to view add

<input name="ids" type="checkbox" class="sub_chk" data-id="{{$item->id}}">

Form

 <form action="{{ route('myproductsDeleteAll') }}" method="POST" >
                        @csrf
                        @method('DELETE')
                    <td><input name="ids" type="checkbox" class="sub_chk" data-id="{{$item->id}}"></td>
                        @if($loop->first)
                        <button type="submit"  class="btn btn-primary delete_all">
                            Delete All Selected
                        </button>
                            @endif
                    </form>

Controller

$ids = $request->ids;
        dd($ids);
        Product::where('id',$ids)->delete();

dd

"on" // app\Http\Controllers\ProductController.php:214
Lara_Love's avatar

@christian-qode

Now how should I get all the selected ones? It has become difficult for me https://postimg.cc/RJwD3B6N

with $loop we have 1 btn and 1 product get . but now 7 btn and 1 product get

$ids = $request->ids;
        dd($ids);
        $item = Product::where('ids',$ids);
        $item->delete();

dd

i select 3 item and click btn 2

array:1 [▼ // app\Http\Controllers\ProductController.php:214 0 => "2" ]

Lara_Love's avatar

@christian-qode It didn't work, but I'll try, maybe I asked the question again Sorry, my friend, if I bothered you. It was fixed with your help. Thanks for all your hard work

jaseofspades88's avatar

I might advise you search for some videos that help you learn what you need to do here. Laracasts is full of people who've invested their time watching videos, learning about the different techniques available to you and they're the ones who are simply paraphrasing what they've either learned before or by watching videos.

Why not cut out the middle man? We're all happy to help but there's a pattern I see time and time again on Laracasts, it goes like this:

Person 1: I have a problem Person 2: Please show us some code Person 1: 'Shows' the problem Person 2: Have you tried this? Person 1: Don't work Person 2: Have you tried this? Person 1: Don't work Person 2: Have you tried this? Person 1: Don't work .... you get the idea

Don't you think you'd feel so much more empowered by retaining some of the advice and learning how to fix the problem with their help rather than expecting one of the hardworking chaps who perhaps have 10 minutes a day to spend writing a fully custom solution for you, do just that?

1 like
Lara_Love's avatar

These are the results of 2 different studies. It is not from Laracast. I am not happy to take other people's time. I am so embarrassed that sometimes someone has to sit and look at my codes to know what the problem is and solve it, and I am even more upset that sometimes several people focus on a problem and only one person can be given an excellent score in Laracast.

    public function deleteAll(Request $request)

    {
        $dd =Product::whereIn('id', $request->get('ids'))->delete();

//dd($dd);
//        return response("Selected post(s) deleted successfully.", 200);

//        $item = Product::findOrFail($request->ids);
//        $item->delete();

//        $ids = $request->get('ids');
//        $ids = $request->ids;
//        dd($ids);
//        $item = Product::where('ids',$ids);
//        $item->delete();
//        dd($ids);
//        DB::table("products")->where('ids',$ids)->delete();
//        DB::table("products")->whereIn('id',explode(",",$ids))->delete();
//        return response()->json(['success'=>"Products Deleted successfully."]);
        return redirect()->back()->with('success','OK');
    }

Script

    <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(",");
                        // console.log(join_selected_values);
                        $.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>
{{--    <script type="text/javascript">--}}
{{--        $(document).ready(function() {--}}

{{--            $("#posts-table").TableCheckAll();--}}

{{--            $('#multi-delete').on('click', function() {--}}
{{--                var button = $(this);--}}
{{--                var selected = [];--}}
{{--                $('#posts-table .check:checked').each(function() {--}}
{{--                    selected.push($(this).val());--}}
{{--                });--}}

{{--                Swal.fire({--}}
{{--                    icon: 'warning',--}}
{{--                    title: 'Are you sure you want to delete selected record(s)?',--}}
{{--                    showDenyButton: false,--}}
{{--                    showCancelButton: true,--}}
{{--                    confirmButtonText: 'Yes'--}}
{{--                }).then((result) => {--}}
{{--                    /* Read more about isConfirmed, isDenied below */--}}
{{--                    if (result.isConfirmed) {--}}
{{--                        $.ajax({--}}
{{--                            type: 'post',--}}
{{--                            headers: {--}}
{{--                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')--}}
{{--                            },--}}
{{--                            url: button.data('route'),--}}
{{--                            data: {--}}
{{--                                'selected': selected--}}
{{--                            },--}}
{{--                            success: function (response, textStatus, xhr) {--}}
{{--                                Swal.fire({--}}
{{--                                    icon: 'success',--}}
{{--                                    title: response,--}}
{{--                                    showDenyButton: false,--}}
{{--                                    showCancelButton: false,--}}
{{--                                    confirmButtonText: 'Yes'--}}
{{--                                }).then((result) => {--}}
{{--                                    window.location='/posts'--}}
{{--                                });--}}
{{--                            }--}}
{{--                        });--}}
{{--                    }--}}
{{--                });--}}
{{--            });--}}

{{--            $('.delete-form').on('submit', function(e) {--}}
{{--                e.preventDefault();--}}
{{--                var button = $(this);--}}

{{--                Swal.fire({--}}
{{--                    icon: 'warning',--}}
{{--                    title: 'Are you sure you want to delete this record?',--}}
{{--                    showDenyButton: false,--}}
{{--                    showCancelButton: true,--}}
{{--                    confirmButtonText: 'Yes'--}}
{{--                }).then((result) => {--}}
{{--                    /* Read more about isConfirmed, isDenied below */--}}
{{--                    if (result.isConfirmed) {--}}
{{--                        $.ajax({--}}
{{--                            type: 'post',--}}
{{--                            headers: {--}}
{{--                                'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')--}}
{{--                            },--}}
{{--                            url: button.data('route'),--}}
{{--                            data: {--}}
{{--                                '_method': 'delete'--}}
{{--                            },--}}
{{--                            success: function (response, textStatus, xhr) {--}}
{{--                                Swal.fire({--}}
{{--                                    icon: 'success',--}}
{{--                                    title: response,--}}
{{--                                    showDenyButton: false,--}}
{{--                                    showCancelButton: false,--}}
{{--                                    confirmButtonText: 'Yes'--}}
{{--                                }).then((result) => {--}}
{{--                                    window.location='/posts'--}}
{{--                                });--}}
{{--                            }--}}
{{--                        });--}}
{{--                    }--}}
{{--                });--}}

{{--            })--}}
{{--        });--}}
{{--    </script>--}}

Please or to participate in this conversation.