首页 > 解决方案 > 禁用两条路由的调用

问题描述

对于我的项目,我需要动态路由,因为 URL 中的 {slug} 可以指向多个资源。

/shoes - poinst to category
/black-slippers - points to product

除了通配符路由,我还有几(50)条静态路由(都在routes/web.php中的通配符路由之前定义)但是现在,当被称为静态路由时,也会执行通配符路由,例如:

Route::get('/profile', [\App\Http\Controllers\Frontend\UserProfileController::class, 'show'])->name('profile.show');
Route::get('{address}', [\App\Http\Controllers\Core\WebaddressController::class, 'resolveAddress'])->where('address', '.*');

在浏览器中显示配置文件页面(正确),但在 SQL 查询中我看到,在 WebaddressController@resolveAddress 中调用的查询也被执行。

如果我评论通配符 Route,查询就会消失。

我该怎么做才能不执行通配符路由?谢谢

请不要建议更改路线样式,我不能,这是要求的形式。

标签: laravelroutes

解决方案


您可以在语句中使用正则表达式从通配符路由中排除一些关键字where

Route::get(
    '{address}', 
    [\App\Http\Controllers\Core\WebaddressController::class, 'resolveAddress']
)
    ->where('address', '^(?!profile|other-static-route)$');

关键字列表不必硬编码。您可以自己创建一个列表,或者从您定义的路由中解析关键字,如下所示:

use Illuminate\Support\Str;

$keywords = collect(Route::getRoutes())
    ->map(function ($route) {
        return Str::afterLast($route->uri(), '/');
    })
    ->filter(function ($keyword) {
        return !Str::endsWith($keyword, '}');
    })
    ->implode('|');

像这样将它们添加到 where 语句中:

->where('address', '^(?!' . $keywords . ')$');

推荐阅读