为什么删除请求使用 ajax 在 Laravel 中返回 404

塞缪尔网

这是我的 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,
    ]);
    
});

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章