如何在Laravel 5中验证路由参数? [英] How to validate Route Parameters in Laravel 5?

查看:373
本文介绍了如何在Laravel 5中验证路由参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您知道Laravel 5改变了调用validator的方式,以前的方式是调用validator facade,但是现在基本Controller类中有ValidatesRequests特性,但是validate方法接受请求作为值数组,但是在定义路由参数时,这些值未存储在Request中,那么如何验证这些参数?

As you know Laravel 5 changes the way you call the validator, the old way is calling the validator facade, but now there is the ValidatesRequests trait in base Controller class, but the validate method accepts the request as the values array, but when you define your route parameters, these values are not stored in Request, so how can I validate those parameters ?

路线:

Route::get('/react-api/{username}', 'ProfileController@getUsername');

控制器:

public function getUsername(Request $request, $username)
{
     $v = $this->validate($request, ['username' => 'required']);
}

那么,我该如何验证用户名参数呢?

So, the question how can i validate this username parameter ?

推荐答案

Manix的答案对我不起作用,我遇到的问题与Iliyass相同.问题是路由参数不会自动提供给FormRequest.我最终在特定的FormRequest类中重写了all()函数:

Manix's answer wasn't working for me, I was having the same issues as Iliyass. The issue is route parameters aren't automatically available to the FormRequest. I ended up overriding the all() function in my particular FormRequest Class:

public function all()
{
    // Include the next line if you need form data, too.
    $request = Input::all();
    $request['username'] = $this->route('username');
    return $request
}

然后,您可以像往常一样编写规则:

Then you can code rules as normal:

public function rules()
{
    return [
        'username' => 'required',
    ];
}

这篇关于如何在Laravel 5中验证路由参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆