Home > Back-end >  Why does delete request return a 404 in Laravel using ajax
Why does delete request return a 404 in Laravel using ajax

Time:04-10

This is the route inside my web.php file It says 404 Not found on the route http://127.0.0.1:8000/categories/delete

Route::middleware(["auth"])->group(function () {
    Route::resources([
        'categories' => CategoryController::class,
        'posts' => PostsController::class,
    ]);
    
    // this is the route i am targeting
    Route::delete("/categories/delete", [CategoryController::class, "delete"])->name("categories.delete"); 
});

This is the ajax request to the route inside my index.blade.php file

<button id="deleteAll"  type="button">
    <x-heroicon-o-trash  />
</button>

<script>
    $(function(){
        $("#check-all").click(function(){
            $(".item-check").prop("checked", $(this).prop('checked'));
        });

        // This is the click event to delete a category
        $("#deleteAll").click(function(e){
            e.preventDefault();

            let allIds = [];
            $("input:checkbox[name=catId]:checked").each(function(){
                allIds.push($(this).val());
            });

            $.ajax({
                url: "{{ route('categories.delete') }}",
                type: "DELETE",
                data: {
                    _token: $("input[name=_token]").val(),
                    ids: allIds
                },
                success: function(response){
                    $.each(ids, function(key, val){
                        $("#row-" val).remove(); 
                    })
                }
            });
        });
    });
</script>

Here is the delete function within my CategoryController

public function delete(Request $request)
{
   dd($request->all());
}

CodePudding user response:

In think you must change your routes order:

your web.php file could be like this:

Route::middleware(["auth"])->group(function () {

    // this is the route i am targeting
    Route::delete("/categories/delete", [CategoryController::class, "delete"])->name("categories.delete"); 

    Route::resources([
        'categories' => CategoryController::class,
        'posts' => PostsController::class,
    ]);
    
});

If you want to add custom route to resource routing, you must use custom ones before resource route. for more information go to resource.

  • Related