首页 > 解决方案 > 仅在一条路线 Laravel 7 中未找到 404 错误

问题描述

我正在重构我的代码并在一条路线中收到404 Page not found错误。我尝试了所有可能的解决方案,但没有运气。我的路线如下:

Route::prefix('admin')->group(function () {
    .... other routes
    
    Route::prefix('product')->group(function () {
        .... other routes

        Route::prefix('category')->group(function () {
            Route::get('/', function () {
                dd('check');
            });

            <!-- Route::get('/', 'ProductCategoryController@index')->name('product_category_index'); -->
           
            .... other routes

        });
    });
});

在调试栏中,我得到了异常:

模型 [App\Product] 类别 F:\bvend\bvend.web\vendor\laravel\framework\src\Illuminate\Database\Eloquent\Builder.php#389 Illuminate\Database\Eloquent\ModelNotFoundException 没有查询结果

我的代码中不再有App\Category 模型。相反,我有App\ProductCategory

我不知道错误是什么。请帮忙。

标签: laravellaravel-5laravel-7

解决方案


问题是两条路线相互冲突。

假设您有以下两条路线,顺序如下:

admin/product/{product}

admin/product/category

当您尝试访问时,您admin/product/category实际上是在使用路由参数的值进行访问。admin/product/{product}category{product}

这就是您收到错误的原因No query results for model [App\Product] category,它正在尝试使用 id 搜索产品category

现在,如果您更改顺序:

admin/product/category

admin/product/{product}

现在该路由admin/product/category的优先级高于admin/product/{product},因此您实际上可以访问您想要的路由,而不是匹配到该admin/product/{product}路由中。


推荐阅读