首页 > 解决方案 > 通过删除 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位。我该怎么办?

标签: phpregexlaravelurl-routinglaravel-routing

解决方案


这是不可能的,因为 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}


推荐阅读