如何在 Laravel 5 中验证路由参数?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29578153/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 11:20:23  来源:igfitidea点击:

How to validate Route Parameters in Laravel 5?

phpvalidationlaravellaravel-5

提问by Iliyass Hamza

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 ValidatesRequeststrait in base Controller class, but the validatemethod 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 ?

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

Edit:

编辑:

Route:

路线:

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

Controller:

控制器:

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

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

那么,问题是如何验证这个用户名参数?

回答by Mitch

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:

Manix 的回答对我不起作用,我遇到了与 Iliyass 相同的问题。问题是路由参数不能自动用于 FormRequest。我最终在我的特定 FormRequest 类中覆盖了 all() 函数:

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',
    ];
}

回答by Mahdyfo

public function listTurns($doctor_id, $limit, $offset){
        $r = [
            'doctor_id' => $doctor_id,
            'limit' => $limit,
            'offset' => $offset,
        ];

        $validator = Validator::make($r, [
            'doctor_id' => 'required|numeric|min:1|exists:doctors,id',
            'limit' => 'required|numeric|min:1',
            'offset' => 'required|numeric|min:0',
        ]);
}

回答by manix

Supposue the following route:

假设有以下路线:

Route::get('profile/{id}', 'ProfileController@show');

You can still validate idparameter as L4 way:

您仍然可以id以 L4 方式验证参数:

public function show(){
    $validator = \Validator::make(
        \Input::all(),
        [
             'id' => ['required', 'numeric']
        ]
    );

    // run validator here
}

If you need to validate concrete data, take a look the following example:

如果您需要验证具体数据,请查看以下示例:

public function getUsername(Request $request, $username)
{
    $validator = \Validator::make(
        [
             'username' => $username
        ],
        [
             'username' => ['required']
        ]
    );

    // run the validator here
}

L5 let you do in two other ways. The first one, using a generic Requestclass injected in the controller:

L5 让你做另外两种方式。第一个,使用Request注入控制器的泛型类:

public function show(Request $request){
    $this->validate($request, [
        'id' => ['required', 'numeric']
    ]);

    // do stuff here, everything was ok
}

In L5 you are allowed to call validate()functions that receive the request and the rules to run over it. This functions is in charge of run rules, if some rule fails, then the user is redirected to previous request

在 L5 中,您可以调用validate()函数来接收请求和运行它的规则。这个函数负责运行规则,如果某个规则失败,那么用户被重定向到之前的请求

Finally, as second option, you can use Form request validation. Remember, every GET and POST value can be accessed via Request class

最后,作为第二个选项,您可以使用表单请求验证。请记住,每个 GET 和 POST 值都可以通过 Request 类访问

回答by Elqolbi

use Validator;

public function getUsername($username)
{
    $validator = Validator::make(['username' => $username], [
      'username' => 'required|string'
    ]);

    if ($validator->fails()) {
      return response()->json(['success' => false, 'errors' => $validator->messages()], 422);
    }
}

回答by Gabriel Eduardo Caraballo Moya

use Illuminate\Support\Facades\Validator;

public function getUsername($username) {
    $validator = Validator::make(['username' => $username], [
      'username' => 'required'
    ]);

    if ($validator->fails()) {
      return response()->json(['status' => 'error'], 400);
    }
}