据我所知,您希望对api和Web请求应用相同的逻辑,您可能只想(a)验证Web请求的表单和/或(b)将响应包装在json中以获取API请求 .
我认为最好的方法是 refer to the same controller and method for both web and api requests ,例如:
在您的routes / web.php中,添加 Route::post('/register', 'RegistrationController@register );`
在你的routes / api.php中,添加 Route::post('/register', 'RegistrationController@register )`
因此,最终两个请求(api / register和/ register)都使用相同的控制器和方法 .
现在,在您的控制器中,您可以根据请求执行额外操作,如下所示:
public function register(Request $request) {
if(!$request->expectsJson()) { // you may want to swap this with $request->isJson() depending on the HTTP headers for your app
$this->validateWebRegistration($request); // your validation logic specific to web requests here
}
// common logic here (including validation); store result as $result
if($request->expectsJson()) { // based on HTTP headers as above
return response()->json($result);
} else {
return view('register', $result);
}
}