Laravel routing, slug with multiple possibilities

╄→гoц情女王★ 提交于 2019-12-13 03:47:38

问题


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?


回答1:


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
});



回答2:


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

above approach is more flexible than previous one




回答3:


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);
});


来源:https://stackoverflow.com/questions/54361948/laravel-routing-slug-with-multiple-possibilities

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