我在 route / api.php :
中有这条路线 Route::post('/register', 'LoginController@register');
我的 LoginController
class LoginController extends Controller {
public function register(Request $request) {
$this->validate($request, // <-- using this will return the view
// from **web.php** instead of the expected json response.
[
'email' => 'required|email',
'firstName' => 'required|alpha_dash',
'lastName' => 'required',
'password' => 'required|confirmed',
]);
$input = $request->all();
//$plain_password = $input['password'];
$input['uuid'] = uuid();
$input['password'] = Hash::make($input['password']);
$user = User::create($input);
dd($errors);
$response['succes'] = true;
$response['user'] = $user;
return response($response);
}
}
为什么添加验证调用会改变行为以返回我的视图/错误的路由。我希望api也能验证我的请求,而不仅仅是我的“前端”。
答案 0 :(得分:1)
当您从控制器使用Laravel
的{{1}}方法时,如果验证失败,它会自动处理/采取步骤。因此,根据所需的内容类型/请求类型,它会确定是重定向还是重定向到给定网址还是发送validate
响应。最终,当你的验证失败时会发生以下事情:
json
因此,如果第一个protected function buildFailedValidationResponse(Request $request, array $errors)
{
if ($request->expectsJson()) {
return new JsonResponse($errors, 422);
}
return redirect()->to($this->getRedirectUrl())
->withInput($request->input())
->withErrors($errors, $this->errorBag());
}
语句为真,那么您将收到if
响应,如果您发送json
请求,则该回复为真如果您附加ajax
标头,请求接受accept
响应(从远程服务器请求时)。因此,请确保您的请求符合要求。
或者,您可以使用Validator组件手动验证请求,如果失败则会明确返回json
响应。