【问题标题】:Why route in web.php conflicts due to a parameter passing in laravel 8为什么 web.php 中的路由由于 laravel 8 中传递的参数而发生冲突
【发布时间】:2022-01-31 14:44:46
【问题描述】:

我在 web.php 中有路由

Route::get('{cat}',[WebsiteController::class,'dbCategories'])->name('dbCategories');

{cat} 是要展示其产品的特定类别的 slug。

我对这里的另一条路线有疑问

Route::get('blogs',[WebsiteController::class,'show_blogs_toWebsite'])->name('show_blogs_toWebsite');

当我到达这条路线时,它会转到第一个。我如何区分这两者。 请帮我。谢谢。

【问题讨论】:

    标签: laravel routes


    【解决方案1】:
    1. 您可以通过在 {cat} 之前或之后添加一个字符串来更改第一个路由 url,例如 Route::get('/category/{cat}',[WebsiteController::class,'dbCategories'])->name('dbCategories')

    另外,如果你改变路线的顺序,它会正常工作

    注意:测试前运行 php artisan route:clear 命令

    【讨论】:

    • 是的,我明白你的意思,我试过了,效果很好。但我想知道为什么当我没有在任何其他路由中发送 {cat} 参数时调用第一个路由
    • @muhammadadnan {cat} 是一个变量,可以有任何值(包括blogs)所以它基本上与blogs 路由冲突
    • @muhammadadnan 基本上您不是在发送参数,而是在构建路由 URL。打开路由时,Laravel 将采用与 URL 匹配的第一个路由。
    【解决方案2】:

    通常应该首先声明具有优先权的那个,例如

    Route::get('blogs',[WebsiteController::class,'show_blogs_toWebsite'])->name('show_blogs_toWebsite');
    Route::get('{cat}',[WebsiteController::class,'dbCategories'])->name('dbCategories');
    

    您还有其他一些选择,例如在路由处理程序中处理这个:

    Route::get('{cat}',function ($cat) {
        if ($cat === 'blogs') return app()->call([WebsiteController::class,'show_blogs_toWebsite']); 
        return app()->call([WebsiteController::class,'dbCategories']);
    });
    

    这样做的缺点是您丢失了路线名称。

    另一种选择是指定一个正则表达式来匹配{cat},例如

    Route::get('{cat}',[WebsiteController::class,'dbCategories'])
        ->name('dbCategories')
        ->where('cat', '^((?!blogs).)*$');
    Route::get('blogs',[WebsiteController::class,'show_blogs_toWebsite'])
        ->name('show_blogs_toWebsite');
    

    上面的正则表达式来自https://stackoverflow.com/a/406408/487813

    【讨论】:

      猜你喜欢
      • 2018-12-22
      • 2019-07-10
      • 2018-10-01
      • 1970-01-01
      • 2017-04-15
      • 2018-05-23
      • 1970-01-01
      • 1970-01-01
      • 2018-11-30
      相关资源
      最近更新 更多