laravel - 禁用两条路由的调用
问题描述
对于我的项目,我需要动态路由,因为 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,查询就会消失。
我该怎么做才能不执行通配符路由?谢谢
请不要建议更改路线样式,我不能,这是要求的形式。
解决方案
您可以在语句中使用正则表达式从通配符路由中排除一些关键字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 . ')$');
推荐阅读
- sql - 在 SQL Server 存储过程中使用 IF
- android - 更新哈希映射值android firebase实时数据库
- javascript - 如何制作以不变的速率重复的多个 D3.js 转换?
- c - g_timeout_add:返回值始终为 0
- java - 线程安全的自动填充参考 - 同步与原子参考与软/弱参考
- javascript - 在随机位置生成方块
- javascript - 如何在`javascript中引用变量
- apache-kafka - 可以在 Kafka Streams 中进行自我加入吗?
- java - Spring Hibernate - 使用现有类别保存笑话
- c++ - OpenMP 4.5 任务依赖和执行顺序