Php 从Laravel中的验证程序发送自定义响应
我有一个注册用户路径,它采用Php 从Laravel中的验证程序发送自定义响应,php,laravel,laravel-5,laravel-5.2,laravel-5.3,Php,Laravel,Laravel 5,Laravel 5.2,Laravel 5.3,我有一个注册用户路径,它采用名称,电子邮件和密码。如果数据正确,即存在唯一的电子邮件和参数,则它可以正常工作,但如果用户已注册,则Laravel会以自己的格式发送自动错误消息。我希望返回格式在成功或失败的情况下保持一致 成功注册返回数据: { "status": "success", "token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6Ly8xMjcuMC4wLjE6ODAwMC9h
名称
,电子邮件
和密码
。如果数据正确,即存在唯一的电子邮件和参数,则它可以正常工作,但如果用户已注册,则Laravel会以自己的格式发送自动错误消息。我希望返回格式在成功或失败的情况下保持一致
成功注册返回数据:
{
"status": "success",
"token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjUsImlzcyI6Imh0dHA6Ly8xMjcuMC4wLjE6ODAwMC9hcGkvYXV0aC9yZWdpc3RlciIsImlhdCI6MTUyMTI3NTc5MiwiZXhwIjoxNTIxMjc5MzkyLCJuYmYiOjE1MjEyNzU3OTIsImp0aSI6Ik1wSzJSYmZYU1dobU5UR0gifQ.fdajaDooBTwP-GRlFmAu1gtC7_3U4ygD1TSBIqdPHf0"
}
但如果出现错误,它会以其他格式发送数据
{"message":"The given data was invalid.","errors":{"email":["The email has already been taken."]}}
我希望两者保持一致。成功返回数据很好。但如果发生故障,我想自定义数据。大概是这样的:
{"status":"error","message":"The given data was invalid.","errors":{"email":["The email has already been taken."]}}
基本上,我需要status
param与每个响应一起出现
另外,在使用Postman时,我有一个查询,当出现错误时,输出是纯HTML。HTML页面是默认的Laravel页面。另一方面,当angular发送相同的请求时,错误是json格式,我刚刚粘贴在上面。
因为angular在任何情况下都会得到JSON响应,所以对我来说都很好。但为什么邮递员不给我看那个反应呢
寄存器控制器:
public function register(RegisterRequest $request)
{
$newUser = $this->user->create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
]);
if (!$newUser) {
return response()->json(['status'=>'error','message'=>'failed_to_create_new_user'], 500);
}
return response()->json([
'status' => 'success',
'token' => $this->jwtauth->fromUser($newUser)
]);
}
注册请求处理程序:
public function authorize()
{
return true;
}
/**
* Get the validation rules that apply to the request.
*
* @return array
*/
public function rules()
{
return [
'name' => 'required',
'email' => 'required | email | unique:users,email',
'password' => 'required'
];
}
如果我理解正确,您总是在没有“状态”键的情况下得到错误响应 您当前的代码会发生以下几件事:
- RegisterController@register(RegisterRequest$请求)由路由调用
- Laravel看到您使用RegisterRequest类作为参数,并将为您实例化该类李>
- 实例化这个类意味着它将直接验证规则李>
- 如果不符合规则,laravel将直接响应发现的错误李>
- 此响应将始终位于laravel的默认“布局”中,代码在此停止李>
public function register(Illuminate\Http\Request $request)
{
//Define your validation rules here.
$rules = [
'name' => 'required',
'email' => 'required | email | unique:users,email',
'password' => 'required'
];
//Create a validator, unlike $this->validate(), this does not automatically redirect on failure, leaving the final control to you :)
$validated = Illuminate\Support\Facades\Validator::make($request->all(), $rules);
//Check if the validation failed, return your custom formatted code here.
if($validated->fails())
{
return response()->json(['status' => 'error', 'messages' => 'The given data was invalid.', 'errors' => $validated->errors()]);
}
//If not failed, the code will reach here
$newUser = $this->user->create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
]);
//This would be your own error response, not linked to validation
if (!$newUser) {
return response()->json(['status'=>'error','message'=>'failed_to_create_new_user'], 500);
}
//All went well
return response()->json([
'status' => 'success',
'token' => $this->jwtauth->fromUser($newUser)
]);
}
现在,不符合验证规则仍然会触发错误,但您的错误,而不是laravel的内置错误:)
我希望有帮助 如果我理解正确,您总是在没有“状态”键的情况下得到错误响应 您当前的代码会发生以下几件事:
- RegisterController@register(RegisterRequest$请求)由路由调用
- Laravel看到您使用RegisterRequest类作为参数,并将为您实例化该类李>
- 实例化这个类意味着它将直接验证规则李>
- 如果不符合规则,laravel将直接响应发现的错误李>
- 此响应将始终位于laravel的默认“布局”中,代码在此停止李>
public function register(Illuminate\Http\Request $request)
{
//Define your validation rules here.
$rules = [
'name' => 'required',
'email' => 'required | email | unique:users,email',
'password' => 'required'
];
//Create a validator, unlike $this->validate(), this does not automatically redirect on failure, leaving the final control to you :)
$validated = Illuminate\Support\Facades\Validator::make($request->all(), $rules);
//Check if the validation failed, return your custom formatted code here.
if($validated->fails())
{
return response()->json(['status' => 'error', 'messages' => 'The given data was invalid.', 'errors' => $validated->errors()]);
}
//If not failed, the code will reach here
$newUser = $this->user->create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => bcrypt($request->get('password'))
]);
//This would be your own error response, not linked to validation
if (!$newUser) {
return response()->json(['status'=>'error','message'=>'failed_to_create_new_user'], 500);
}
//All went well
return response()->json([
'status' => 'success',
'token' => $this->jwtauth->fromUser($newUser)
]);
}
现在,不符合验证规则仍然会触发错误,但您的错误,而不是laravel的内置错误:)
我希望有帮助 这就是我想到的:
function validate(array $rules)
{
$validator = Validator::make(request()->all(), $rules);
$errors = (new \Illuminate\Validation\ValidationException($validator))->errors();
if ($validator->fails()) {
throw new \Illuminate\Http\Exceptions\HttpResponseException(response()->json(
[
'status' => false,
'message' => "Some fields are missing!",
'error_code' => 1,
'errors' => $errors,
], \Illuminate\Http\JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
}
创建助手目录(App\Helpers
)并将其添加到文件中。别忘了将其添加到composer.json中
"autoload": {
"files": [
"app/Helpers/system.php",
],
},
现在,您可以在控制器中调用validate()
,并获得所需的:
validate([
'email' => 'required|email',
'password' => 'required|min:6|max:32',
'remember' => 'nullable|boolean',
'captcha' => 'prod_required|hcaptcha',
]);
这就是我想到的:
function validate(array $rules)
{
$validator = Validator::make(request()->all(), $rules);
$errors = (new \Illuminate\Validation\ValidationException($validator))->errors();
if ($validator->fails()) {
throw new \Illuminate\Http\Exceptions\HttpResponseException(response()->json(
[
'status' => false,
'message' => "Some fields are missing!",
'error_code' => 1,
'errors' => $errors,
], \Illuminate\Http\JsonResponse::HTTP_UNPROCESSABLE_ENTITY));
}
}
创建助手目录(App\Helpers
)并将其添加到文件中。别忘了将其添加到composer.json中
"autoload": {
"files": [
"app/Helpers/system.php",
],
},
现在,您可以在控制器中调用validate()
,并获得所需的:
validate([
'email' => 'required|email',
'password' => 'required|min:6|max:32',
'remember' => 'nullable|boolean',
'captcha' => 'prod_required|hcaptcha',
]);
在Laravel 8中,我添加了带有“success”的自定义invalidJson:false: 在app/Exceptions/Handler.php中:
/**
* Convert a validation exception into a JSON response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
protected function invalidJson($request, ValidationException $exception)
{
return response()->json([
'success' => false,
'message' => $exception->getMessage(),
'errors' => $exception->errors(),
], $exception->status);
}
在Laravel 8中,我添加了带有“success”的自定义invalidJson:false: 在app/Exceptions/Handler.php中:
/**
* Convert a validation exception into a JSON response.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Validation\ValidationException $exception
* @return \Illuminate\Http\JsonResponse
*/
protected function invalidJson($request, ValidationException $exception)
{
return response()->json([
'success' => false,
'message' => $exception->getMessage(),
'errors' => $exception->errors(),
], $exception->status);
}