为什么删除请求 return 在 Laravel 中使用 ajax 的 404

Why does delete request return a 404 in Laravel using ajax

这是我的 web.php 文件中的路径 它说 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"); 
});

这是对我的 index.blade.php 文件中的路由的 ajax 请求

<button id="deleteAll" class="border-0" type="button">
    <x-heroicon-o-trash class="w-6 h-6 text-red-600" />
</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>

这是我的 CategoryController 中的删除功能

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

认为您必须更改路线顺序:

您的 web.php 文件可能是这样的:

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,
    ]);
    
});

如果要在资源路由中添加自定义路由,必须在资源路由之前使用自定义路由。 如需更多信息,请访问 resource.