How to use the same route for multiple options (Laravel 5)

时间:2017-08-13 13:59:37

标签: php regex laravel-5 controller routes

I need to have a route for multiple pricing levels (bronze, silver and gold). Currently I have:

Route::get('/{level}', [ 'as' => 'pricing', 'uses' => 'PagesController@pricing']);

However, this matches anything, how can I make so it matches only: bronze, silver or gold while reading the value in my controller like this:

public function pricing($level) {
    $data['level'] = $level;
    return View::make('pages.pricing', $data);
}

1 个答案:

答案 0 :(得分:3)

我建议只使用switch-case语句(或if/else)在函数内处理它。

public function pricing() {
    switch ($level) {
        case 'silver':
            // do something
            break;
        case 'bronze':
            // do something
            break;
        case 'gold':
            // do something
            break;
        default:
            throw new \Exception('not one of bronze. silver or gold');
    }
}

但是你可以写

Route::get('/{level}', [ 'as' => 'pricing', 'uses' => 'PagesController@pricing'])->where('level', '(bronze|silver|gold)');