Laravel5 如何验证路由中的变量

1. 将路由中的变量添加到请求对象中,默认laravel的请求对象中不包含路由中的变量,我们重写all()方法即可

/**
 * @return array
 */
public function rules(){
    return [
        'slug' => 'required|exists:articles,slug',
    ];
}

/**
 * Add parameters to be validated
 * 
 * @return array
 */
public function all(){
    return array_replace_recursive(
        parent::all(),
        $this->route()->parameters()
    );
}

2. 使用路由-模型绑定

匹配的Article实例将会传递给控制器

Last updated

Was this helpful?