Laravel routing, slug with multiple possibilities

2019-08-21 09:43发布

问题:

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