简体   繁体   English

Laravel 5 API请求验证

[英]Laravel 5 API request validation

I'm working with Laravel 5 API. 我正在使用Laravel 5 API。 I have a few methods with similar request parameters 我有几种具有类似请求参数的方法

For example to check the licence status or get the settings file you need to provide the ?serial=licence_serial_number parameter. 例如,要检查许可证状态或获取设置文件,您需要提供?serial=licence_serial_number参数。

I need to return 400 error code, when the user didn't provide the serial parameter, and 403 error code, when the user is trying to get information about the licence of another user. 当用户未提供serial参数时,我需要返回400错误代码,而当用户试图获取有关另一用户许可证的信息时,我需要返回403错误代码。

What is the best practice to organise validation and error handling of these kind of requests? 组织此类请求的验证和错误处理的最佳实践是什么?

  • Should I make a middleware to check if the user has provided ?serial ? 我应该制作一个中间件来检查用户是否提供了?serial吗?
  • Or should I make a different Laravel 5 FormRequest class for every method? 还是应该为每个方法制作一个不同的Laravel 5 FormRequest类?
  • Or should I validate it directly in a controller with: 或者我应该直接在控制器中使用以下命令验证它:
    if (..) {return response()->json([..], 400);}

$ request-> wantJson(),带有标头Accept = application / json的请求,将告诉Laravel返回json验证错误,而不是返回有错误的goback

It depends on a few things acctualy: 它取决于一些事情:

If your always validating the same thing for all requests: Go With a Middleware Solution. 如果您始终对所有请求都验证相同的内容:使用中间件解决方案。

But if some or multiple requests validate different things then I would advise on using the new FormRequest from Laravel. 但是,如果某些或多个请求验证了不同的内容,那么我建议使用Laravel中的新FormRequest。

It handles the validation for your request perfectly, and also allows you the define the error responses per request. 它可以完美地处理您的请求验证,还可以定义每个请求的错误响应。

Also a middleground is an option, Let middleware validate the thing that needs to be validated always. 中间件也是一个选项,让中间件验证始终需要验证的事物。 And FormRequests to handle the variable validation. 和FormRequests处理变量验证。

If you have similar FormRequests, consider using inheritance to prevent code duplication like a good SOLID programmer :-) 如果您有类似的FormRequests,请考虑使用继承来防止代码重复,就像一个好的SOLID程序员一样:-)

Middleware will probably be the best choice but you could also use the Request method.Inline validation is a bad practice as its ignore the most basic rule of programming - Dont Repeat Yourself. 中间件可能是最好的选择,但您也可以使用Request方法。内联验证是一种不好的做法,因为它忽略了最基本的编程规则-不要重复自己。

In case you decide go for the request option you aren't supposed to create the authorize method for each class,instead create 1 parent witch will handle this and the other sub classes will just have the rules method. 如果您决定使用request选项,则不应该为每个类创建authorize方法,相反,创建1个父级女巫将处理该方法,而其他子类仅具有rules方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM