php - 通过删除 Laravel 中的多余字符,从斜杠分隔的 url 中提取参数值
问题描述
我在 laravel 框架上为我的 php 服务器创建路由。如何通过剥离不必要的位从斜杠分隔的 url 中提取正确的参数值?
当 url 模式设置为
Route::get('user/{event_id}',function ($event_id){return view('rsvp',['event_id'=>$event_id]);})->where(['event_id'=>'[0-9]+']);
它完全按预期工作。但是,我想解析一个 url 的形式'user/event-description-here5_now-<event_id>
并实现相同的功能。也就是说,我想event_id
在我的 php 文件中使用并忽略该event-description-here5_now
位。我该怎么办?
解决方案
这是不可能的,因为 laravel 路由模型绑定通过通配符工作,并且在尝试从 url 段中提取数字时它不起作用。
为了使其工作,您必须自定义 laravel 路由解析逻辑: https ://laravel.com/docs/5.8/routing#route-model-binding
类似于:
public function boot()
{
parent::boot();
Route::bind('eventslug', function ($value) {
preg_match('/\d+/', strrev($value), $matches);
return Event::find($matches[0]) ?? abort(404);
});
}
或尝试调整网址,如:
user/event-description-here5_now/{event_id}
推荐阅读
- javascript - Fuse.js 在字符串数组中搜索
- java - 无法在 Java Servlet 上上传文件
- python - `django-cognito-jwt` get_public_key 方法中的 TokenValidator 返回无
- mongodb - 带有 ISO-Date %G 的 MongoDB dateFromString 错误
- asp.net-mvc-4 - 使用 Code-First 的另一个模式中的外键在添加迁移时创建了两次引用的表
- c# - 在 ASP.NET C# 中将 Gridview 行转换为列
- javascript - Qt5 - QML - AirLink RV50 - JavaScript:如何在第三方路由器上自动触发组合框和按钮
- python - 在 Pytorch 教程期间发生 ModuleNotFoundError: 'pycocotools._mask'
- python - 使用 if/else 和 for 循环将项目附加到列表理解中的列表
- python - 使用 selenium 读取多个文本元素时出现错误消息