如果参数不是整数,如何以不同方式定义路由

How can I define a route differently if parameter is not integer

我正在使用 Laravel 5 并在本地工作。 我创建了一个参数为 {id} 的路由和另一个具有特定名称的路由,如下所示:

Route::get('contacts/{id}', 'ContactController@get_contact');
Route::get('contacts/new', 'ContactController@new_contact');

我的问题是,如果我尝试访问 localhost/contacts/new,它将自动访问 get_contact 方法。我知道我已经制作了一个 {id} 参数,但是如果我只想在我的参数是整数时调用 get_contact 怎么办?如果不是,请检查它是否是 "new" 并访问 new_contact 方法。然后,如果它不是整数且不是 "new",错误页面 404。

我如何在 Laravel 5 中做到这一点?

感谢您的帮助!

只需将 ->where('id', '[0-9]+') 添加到您希望接受纯数字参数的路由:

Route::get('contacts/{id}', 'ContactController@get_contact')->where('id', '[0-9]+');
Route::get('contacts/new', 'ContactController@new_contact');

阅读更多:http://laravel.com/docs/master/routing#route-parameters

也可以只切换它们,因为路由文件会从上到下遍历所有行,直到找到有效路由。

Route::get('contacts/new', 'ContactController@new_contact');
Route::get('contacts/{id}', 'ContactController@get_contact');

如果您想将该路由限制为纯数字,则标记的解决方案是正确的。

只是在这里添加它,我知道它很旧;)

一个简单的解决方案是使用显式方法。

Route::get('contacts/{id:[0-9]+}', 'ContactController@get_contact');
Route::get('contacts/new', 'ContactController@new_contact');

尽管接受的答案非常好,但通常一个参数会被多次使用,因此您可能希望通过在 RouteServiceProvider.php 中的 boot 函数中定义一个模式来使用 DRY 方法位于 app/Providers 下的文件 (Laravel 5.3 及以后):

 /**
 * Define your route model bindings, pattern filters, etc.
 *
 * @return void
 */
public function boot()
{
    Route::pattern('id', '[0-9]+');

    parent::boot();
}

这样,无论您在哪里使用 {id} 参数,都会应用约束。

创建您自己的请求并添加验证规则。此外,将此请求用作控制器方法的参数

/**
 * Get the validation rules that apply to the request.
 *
 * @return array
 */
public function rules(Request $request)
{
    return [
        'id' => 'required|integer'
    ];
}

/**
 * @return array
 */
public function validationData()
{
    return array_replace_recursive(
        $this->all(),
        $this->route()->parameters()
    );
}

只需更改行的顺序

Route::get('contacts/new', 'ContactController@new_contact');
Route::get('contacts/{id}', 'ContactController@get_contact');

它会起作用的!