Route parameter patterns on routes with similar parameters

本小妞迷上赌 提交于 2019-12-02 06:27:45

问题


I have a few routes that takes a couple of UUIDs as parameters:

Route::get('/foo/{uuid1}/{uuid2}', 'Controller@action');

I want to be able to verify that those parameters are the correct format before passing control off to the action:

Route::pattern('uuid1', '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$');

This works fine. However, I really don't want to repeat that pattern so many times (in the real case I have it repeated 8 times for 8 different UUID route parameters).

I can't do this:

Route::get('/foo/{uuid}/{uuid}', 'Controller@action');

Because that produces an error:

Route pattern "/foo/{uuid}/{uuid}" cannot reference variable name "uuid" more than once.

I can lump them all into a single function call since I discovered Route::patterns:

Route::patterns([
    'uuid1' => '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$',
    'uuid2' => '^[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}$',
]);

But that is still repetitious. Is there a way I can bind multiple pattern keys to a single regular expression?

Ideally I'd like to find a way that avoids something like this:

$pattern = 'uuid regex';
Route::patterns([
    'uuid1' => $pattern,
    'uuid2' => $pattern,
]);

回答1:


There's no built in way to handle this, and I actually think the solution you found is pretty nice. Maybe a bit more elegant would be this:

Route::patterns(array_fill_keys(['uuid1', 'uuid2'], '/uuid regex/'));


来源:https://stackoverflow.com/questions/30242976/route-parameter-patterns-on-routes-with-similar-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!