Laravel routing, slug with multiple possibilities

2019-08-21 09:28发布

Been searching for a while and can't find an answer on if this is possible.

One URL I am trying to make. would be

/location/province-name/city/category

The province name only has a few options. Is there a way to set it up so something like this would work?

/{bc or ab or mn or etc}/{cityname}/{category}

does this make sense?

3条回答
姐就是有狂的资本
2楼-- · 2019-08-21 09:36

What you can do is use a pattern

routes/web.php

Route::pattern('province', '(bc|ab|mn|etc)');

Route::get('/location/{province}/{city}/{category}', function ($province, $city, $category) {
    // TODO do something with your route
});
查看更多
手持菜刀,她持情操
3楼-- · 2019-08-21 09:48
/{bc or ab or mn or etc}/{cityname}/{category}

above approach is more flexible than previous one

查看更多
乱世女痞
4楼-- · 2019-08-21 10:01

You can add validation as,

Route::get('/location/{province}/{city}/{category}', function ($province, $city, $category) {

    // show 'Page Not Found' if $province in not in the available options
    if(!in_array($province, ['bc', 'ab','mn'])) {
        abort(404);
    }

    dd($province, $city, $category);
});
查看更多
登录 后发表回答