返回验证失败,如 none 验证场景中的响应
returning validation fail like response in none validation scenario
所以假设我有 2 个函数,我向 init
函数发送一个 ajax 请求,然后初始化函数调用 check
函数
function init(Request $request){
$this->check($request);
}
function check(Request $request){
$request->validate(['something' => 'required']);
}
在这种情况下,如果验证失败 laravel return 是对 ajax 使用 Status Code: 422
调用的响应,我不需要 return 任何响应
现在如果我想检查其他东西,如果失败我想像验证失败响应一样响应
function cehck(Request $request){
if($somethign_else_failes)
{
return response()->json(['errors' => ['email' => ['The email is invalid.']]], 422);
}
}
但这不会 return 返回 ajax 调用响应...它只会 return 它到 init
函数
我需要在 init
函数
中添加另一个 return
基本上我不想在嵌套函数中有多个 return,如果它在任何级别失败我想 return ajax 在该级别的响应
我愿意
function init(Request $Request){
$this->cehck();
// do the rest of code
}
function check(){
if($something_wrong)
//abort with reponse message
}
而不是像这样的东西
function init(Request $Request){
$response = $this->cehck();
if( $response == failed )
{
//abort with reponse message
}
// do the rest of code
}
function check(){
if($something_wrong)
return failed flag ;
}
答案在这里
use Illuminate\Validation\ValidationException;
throw ValidationException::withMessages(['somefield' => 'something is wrong with this field ']);
所以假设我有 2 个函数,我向 init
函数发送一个 ajax 请求,然后初始化函数调用 check
函数
function init(Request $request){
$this->check($request);
}
function check(Request $request){
$request->validate(['something' => 'required']);
}
在这种情况下,如果验证失败 laravel return 是对 ajax 使用 Status Code: 422
调用的响应,我不需要 return 任何响应
现在如果我想检查其他东西,如果失败我想像验证失败响应一样响应
function cehck(Request $request){
if($somethign_else_failes)
{
return response()->json(['errors' => ['email' => ['The email is invalid.']]], 422);
}
}
但这不会 return 返回 ajax 调用响应...它只会 return 它到 init
函数
我需要在 init
函数
基本上我不想在嵌套函数中有多个 return,如果它在任何级别失败我想 return ajax 在该级别的响应
我愿意
function init(Request $Request){
$this->cehck();
// do the rest of code
}
function check(){
if($something_wrong)
//abort with reponse message
}
而不是像这样的东西
function init(Request $Request){
$response = $this->cehck();
if( $response == failed )
{
//abort with reponse message
}
// do the rest of code
}
function check(){
if($something_wrong)
return failed flag ;
}
答案在这里
use Illuminate\Validation\ValidationException;
throw ValidationException::withMessages(['somefield' => 'something is wrong with this field ']);