php 验证请求时 Laravel 中的 REST API
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23162617/
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
REST API in Laravel when validating the request
提问by Aoi
I'm currently trying out on how to build a RESTful API with Laravel and I'm currently in the process of creating a new user. This is just a test and I'm getting some result when trying to validate the request using validation in Laravel; here is the result:
我目前正在尝试如何使用 Laravel 构建一个 RESTful API,我目前正在创建一个新用户。这只是一个测试,我在尝试使用 Laravel 中的验证来验证请求时得到了一些结果;结果如下:
I've been trying to create a new one by this code:
我一直在尝试通过以下代码创建一个新的:
public function store()
{
$validation = Validator::make(Request::all(),[
'username' => 'required|unique:users, username',
'password' => 'required',
]);
if($validation->fails()){
} else{
$createUser = User::create([
'username' => Request::get('username'),
'password' => Hash::make(Request::get('password'))
]);
}
}
but then I don't know how to return the error in validation. But it keeps on giving me that HTML as showed in the image when I was trying to do the if with validation->fails()
. Is there a way to get the validation in JSON format?
但后来我不知道如何在验证中返回错误。但是当我尝试使用validation->fails()
. 有没有办法以 JSON 格式获取验证?
回答by bhupendraosd
these code will help you, working for me.
这些代码会帮助你,为我工作。
$response = array('response' => '', 'success'=>false);
$validator = Validator::make($request->all(), $rules);
if ($validator->fails()) {
$response['response'] = $validator->messages();
}else{
//process the request
}
return $response;
回答by Jason Lewis
You should probably return errors (which is an instance of Illuminate\Support\MessageBag
) and encode that. A MessageBag
instance allows you to convert it directly to its JSON representation.
您可能应该返回错误(它是 的一个实例Illuminate\Support\MessageBag
)并对其进行编码。一个MessageBag
实例,您可以直接转换成JSON表示。
$errors = $validation->errors();
return $errors->toJson();
Now not to toot my own horn but I've recently developed a RESTful API package for Laravel which does all of this for you and all you need to do is throw a simple exception. See my dingo/apipackage and the Wiki on returning errors. Basically, instead of returning the errors you would throw an exception.
现在不要吹嘘自己的号角,但我最近为 Laravel 开发了一个 RESTful API 包,它为您完成所有这些,您需要做的就是抛出一个简单的异常。请参阅我的dingo/api包和有关返回错误的 Wiki 。基本上,不是返回错误,而是抛出异常。
throw new Dingo\Api\Exception\StoreResourceFailedException('Could not create a new user.', $validation->errors());
It would be represented by the following JSON.
它将由以下 JSON 表示。
{
"message": "Could not create a new user.",
"errors": {
"username": ["The username is already in use."]
}
}
回答by zak.http
Laravel provides out of the box a validation method that you can call from your Controller.
Laravel 提供了一个开箱即用的验证方法,您可以从控制器调用它。
if you check the Laravel Controller
abstract class you will find it uses a trait called ValidatesRequests
如果你检查 LaravelController
抽象类,你会发现它使用了一个叫做ValidatesRequests
abstract class Controller extends BaseController
{
use AuthorizesRequests, DispatchesJobs, ValidatesRequests;
}
So you can use a method $this->validate(Request $request, array $rules);
as you long as your controller class extends the Controller
所以你可以使用一个方法$this->validate(Request $request, array $rules);
,只要你的控制器类扩展控制器
the full method declaration is
完整的方法声明是
public function validate(Request $request, array $rules, array $messages = [], array $customAttributes = [])
{
$validator = $this->getValidationFactory()->make($request->all(), $rules, $messages, $customAttributes);
if ($validator->fails()) {
$this->formatValidationErrors($validator);
}
}
If The $validator fails, the method will throw an error depending on the request type, if it is ajax (in this case you should include in the request headers (Accept application/json
) it will return a JSON response containing the validation errors.
如果 $validator 失败,该方法将根据请求类型抛出错误,如果它是 ajax(在这种情况下,您应该在请求标头中包含 ( Accept application/json
),它将返回包含验证错误的 JSON 响应。
回答by mwal
For laravel 5.5 and up, see docs: AJAX Requests & Validation
对于 Laravel 5.5 及更高版本,请参阅文档:AJAX 请求和验证
TL;DR: On failed validation a json response with a 422 is returned along with the validation error messages. It took me a bit of time to find those validation errors in the response object, so to see the error messages if you're using axios, try this in your browser console:
TL;DR:验证失败时,将返回带有 422 的 json 响应以及验证错误消息。我花了一些时间在响应对象中找到这些验证错误,因此如果您使用的是 axios,要查看错误消息,请在浏览器控制台中尝试以下操作:
axios.post('/api/your-route-here')
.then(response => {
console.log(response.data);
}).catch(error => {
console.log(error.response.data.errors)
});