One way would be to override sendLoginResponse()
and sendFailedLoginResponse()
methods from the AuthenticatesUsers
trait so that you can check if the request is an ajax (or wants json).
In you Auth/LoginController
add:
/**
* Send the response after the user was authenticated.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\Response
*/
protected function sendLoginResponse(Request $request)
{
$request->session()->regenerate();
$this->clearLoginAttempts($request);
if ($request->ajax() || $request->wantsJson()) {
return response()->json([
'user' => $this->guard()->user(),
]);
}
return $this->authenticated($request, $this->guard()->user())
?: redirect()->intended($this->redirectPath());
}
/**
* Get the failed login response instance.
*
* @param \Illuminate\Http\Request $request
* @return \Illuminate\Http\RedirectResponse
*/
protected function sendFailedLoginResponse(Request $request)
{
if ($request->ajax() || $request->wantsJson()) {
return response()->json([
$this->username() => Lang::get('auth.failed'),
], 422);
}
return redirect()->back()
->withInput($request->only($this->username(), 'remember'))
->withErrors([
$this->username() => Lang::get('auth.failed'),
]);
}
This should allow you to keep to same routes
for your project.
Also, if you add dataType: 'json'
it should parse the response for you i.e.:
$.ajax({
data: data,
url: 'http://mywebsite.com/login',
dataType: 'json',
method: 'post',
success:function(response){
console.log('success', response);
},
error: function () {
console.log('error', response)
}
});
Hope this help!