BadMethodCallException: Method App\Http\Controllers\UserController::getAuthenticatedUser does not exist - laravel

When i try to Get the authenticated user data from API i get this error:
BadMethodCallException: Method App\Http\Controllers\UserController::getAuthenticatedUser does not exist. in file D:\OpenServer\OSPanel\domains\Pumpkin\vendor\laravel\framework\src\Illuminate\Routing\Controller.php on line 68
Please help to fix it
My userController:
namespace App\Http\Controllers;
use App\User;
use GuzzleHttp\Psr7\Response;
use Illuminate\Auth\Events\PasswordReset;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\Password;
use Illuminate\Support\Facades\Validator;
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Foundation\Auth\ResetsPasswords;
class UserController extends Controller
{
public function authenticate(Request $request)
{
$credentials = $request->only('email', 'password');
try {
if (! $token = JWTAuth::attempt($credentials)) {
return response()->json(['error' => 'invalid_credentials'], 400);
}
} catch (JWTException $e) {
return response()->json(['error' => 'could_not_create_token'], 500);
}
return response()->json(compact('token'));
}
public function logout()
{
auth()->logout();
return response()->json(['message'=>'Successfully logged out']);
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required|string|max:255',
'email' => 'required|string|email|max:255|unique:users',
'password' => 'required|string|min:6|confirmed',
]);
if($validator->fails()){
return response()->json($validator->errors()->toJson(), 400);
}
$user = User::create([
'name' => $request->get('name'),
'email' => $request->get('email'),
'password' => Hash::make($request->get('password')),
]);
$token = JWTAuth::fromUser($user);
return response()->json(compact('user','token'),201);
}
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
return response()->json(compact('user'));
}
}
My api.php
Route::post('auth/register', 'UserController#register');
Route::post('auth/login', 'UserController#authenticate');
Route::post('auth/recover', 'UserController#recover');
Route::get('open', 'DataController#open');
Route::post('/password/email', 'ForgotPasswordController#sendResetLinkEmail');
Route::post('/password/reset', 'ResetPasswordController#reset');
Route::group(['middleware' => ['jwt.verify']], function() {
Route::get('user', 'UserController#getAuthenticatedUser');
Route::get('closed', 'DataController#closed');
});
Middleware:
<?php
namespace App\Http\Middleware;
use Closure;
use JWTAuth;
use Exception;
use Tymon\JWTAuth\Http\Middleware\BaseMiddleware;
class JwtMiddleware extends BaseMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
return response()->json(['status' => 'Token is Invalid']);
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
return response()->json(['status' => 'Token is Expired']);
}else{
return response()->json(['status' => 'Authorization Token not found']);
}
}
return $next($request);
}
}

Can you provide the full log output from \storage\logs?
Also, sending the router as a parameter to the function may help.
Route::group([
'middleware' => 'jwt.verify'
], function ($router) {
Route::get('user', 'UserController#getAuthenticatedUser');
Route::get('closed', 'DataController#closed');
});

Related

Pass JWT Token in Each API Request

Hello I am working with JWT Token, and I'm testing API using postman, when perform operation using Postman I set bearer header in Header of postman, it works fine with Postman,
But what if I don't want to set it In postman header and pass it from Controller?
Any Solution Will Helpful,
Here is my code,
Controller,
public function login(Request $request)
{
$credentials = $request->only('email', 'password');
$token = auth()->attempt( $credentials);
return $this->createNewToken($token);
}
public function me()
{
$user =$this->getAuthenticatedUser();
return response()->json(array($user));
}
protected function createNewToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 1200,
'user' => auth()->user()
]);
}
public function getAuthenticatedUser()
{
try {
if (! $user = JWTAuth::parseToken()->authenticate()) {
return response()->json(['user_not_found'], 404);
}
} catch (Tymon\JWTAuth\Exceptions\TokenExpiredException $e) {
return response()->json(['token_expired'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\TokenInvalidException $e) {
return response()->json(['token_invalid'], $e->getStatusCode());
} catch (Tymon\JWTAuth\Exceptions\JWTException $e) {
return response()->json(['token_absent'], $e->getStatusCode());
}
return response()->json(compact('user'));
}
Route::post('login', [App\Http\Controllers\NewController::class, 'login'])->name('apisignin');
Route::group([
'middleware' => 'jwt.verify',
'prefix' => 'auth',
], function ($router) {
Route::post('getauth', [App\Http\Controllers\NewController::class, 'getAuthenticatedUser'])->name('getAuthenticatedUser');
Route::post('userProfile', [App\Http\Controllers\NewController::class, 'userProfile']);
Route::post('me', [App\Http\Controllers\NewController::class, 'me']);
Route::post('authheader', [App\Http\Controllers\NewController::class, 'authHeader']);
Route::post('userupdate', [App\Http\Controllers\NewController::class, 'userUpdate']);
Route::post('refresh', [App\Http\Controllers\AuthController::class, 'refresh']);
Route::post('getAuthenticatedUser', [App\Http\Controllers\NewController::class, 'getAuthenticatedUser']);
});
public function handle($request, Closure $next)
{
try {
$user = JWTAuth::parseToken()->authenticate();
} catch (Exception $e) {
if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenInvalidException){
return response()->json(['status' => 'Token is Invalid']);
}else if ($e instanceof \Tymon\JWTAuth\Exceptions\TokenExpiredException){
return response()->json(['status' => 'Token is Expired']);
}else{
return response()->json(['status' => 'Authorization Token not found']);
}
}
return $next($request);
}
According to your question, you need to make an API request from your controller.
In order to put a token there, just use withToken($token) method on Illuminate\Support\Facades\Http facade:
Http::withToken($token)->get($url, $parameters)
Laravel documentation: https://laravel.com/docs/8.x/http-client#bearer-tokens

Auth::user() is null after successful Passport authentication

I am using password for user Authentication, and I after every authentication I assign a secure cookie that stores the passport token. A am being able to successfully authenticate using the Auth::attempt() method, but the Auth::user() is null. Even in the same controller, on the logout() method the user is undefined and I can't even Auth::logout().
Login method:
public function login(Request $request)
{
$request->validate([
'email' => 'required|string|email',
'password' => 'required|string',
]);
$credentials = \request(['email', 'password']);
if (Auth::attempt($credentials)) {
$user = Auth::user();
$token = $user->createToken('Personal Access Token')->accessToken;
$cookie = $this->getSessionCookie($token);
return response()
->json([
'user' => $user,
'token' => $token,
], 200)
->cookie(
$cookie['name'],
$cookie['value'],
$cookie['minutes'],
$cookie['path'],
$cookie['domain'],
$cookie['secure'],
$cookie['httponly'],
$cookie['samesite']
);
} else {
return response()->json([
'error' => 'Invalid Credentials',
], 422);
}
}
Logout method:
public function logout(Request $request)
{
$request->user()->token()->each(function ($token, $key) {
$token->delete();
});
$cookie = \Cookie::forget('auth_token');
Auth::logout();
return response()->json([
'message' => 'Logged out successfully.'
], 200)->withCookie($cookie);
}
Here the Auth::logout() produces Method Illuminate\Auth\RequestGuard::logout does not exist. Otherwise the logout is successful.
My API routes:
Route::group(['prefix' => 'v1'], function() {
// Authentication
Route::post('/login', 'AuthController#login');
Route::post('/register', 'AuthController#register');
Route::post('/password/reset', 'AuthController#sendPasswordResetLink');
Route::post('/password/update', 'AuthController#callResetPassword');
// Articles
Route::get('/articles', 'ArticleController#index');
Route::middleware(['auth.header', 'auth:api'])->group(function () {
// Get Logged in User
Route::get('/user', function (Request $request) {
return $request->user(); // returns the actual logged in user
});
// Articles
Route::post('/articles', 'ArticleController#store');
Route::get('/articles/{id}', 'ArticleController#show');
Route::put('/articles/{id}', 'ArticleController#update');
Route::delete('/articles/{id}', 'ArticleController#destroy');
// Log Out
Route::post('/logout', 'AuthController#logout');
});
});
Example controller where Auth::user() is null:
class ArticleController extends Controller
{
public function index(Request $request)
{
$user = \auth()->user(); // null
$user = Auth::user(); // null
$user = $request->user(); // null
}
}
In index method I know why the user is null since the route is not wrapped in auth:api middleware, but how would I get the auth user in this method even if it's not required.
I am sure I am missing something but I don't know what. I'll be happy to provide more code.
EDIT:
My auth.api middleware:
class AuthenticationHeader
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (!$request->bearerToken()) {
if ($request->hasCookie('auth_token')) {
$token = $request->cookie('auth_token');
$request->headers->add(['Authorization' => 'Bearer ' . $token]);
}
}
return $next($request);
}
}
API Routes
Route::group(['prefix' => 'v1'], function() {
// Authentication
Route::post('/login', 'AuthController#login');
Route::post('/register', 'AuthController#register');
Route::post('/password/reset', 'AuthController#sendPasswordResetLink');
Route::post('/password/update', 'AuthController#callResetPassword');
// Articles
Route::get('/articles', 'ArticleController#index');
Route::middleware(['auth:api'])->group(function () {
// Get Logged in User
Route::get('/user', function (Request $request) {
return $request->user(); // returns the actual logged in user
});
// Articles
Route::post('/articles', 'ArticleController#store');
Route::get('/articles/{id}', 'ArticleController#show');
Route::put('/articles/{id}', 'ArticleController#update');
Route::delete('/articles/{id}', 'ArticleController#destroy');
// Log Out
Route::post('/logout', 'AuthController#logout');
});
});
Auth Controller
<?php
namespace App\Http\Controllers\Api;
use App\Mail\ResetPassword;
use Carbon\Carbon;
use Illuminate\Http\Request;
use App\Http\Controllers\Api\BaseController as BaseController;
use App\User;
use Illuminate\Support\Facades\Auth;
use Validator;
use Illuminate\Support\Facades\Password;
use Illuminate\Foundation\Auth\SendsPasswordResetEmails;
use Illuminate\Foundation\Auth\ResetsPasswords;
//use Illuminate\Foundation\Auth\VerifiesEmails;
//use Illuminate\Auth\Events\Verified;
class AuthController extends BaseController
{
use ResetsPasswords;
/**
* Authenticate api
* #param Request
* #return \Illuminate\Http\Response
*/
public function login(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
'password' => 'required',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors(), 400);
}
$email = $request->input('email');
$password = $request->input('password');
if (Auth::attempt(['email' => $email, 'password' => $password])) {
$user = Auth::user();
if ($user->hasVerifiedEmail()) {
$success['token'] = 'Bearer ' . $user->createToken('MyApp')->accessToken;
$success['user'] = $user->only('id', 'name', 'email', 'avatar');
return $this->sendResponse($success, 'User logged in successfully.');
} else {
return $this->sendError('Please verify your Email.', [], 400);
}
}
return $this->sendError('Wrong Credentials.', [], 400);
}
/**
* Register API
* #param Request
* #return \Illuminate\Http\Response
*/
public function register(Request $request)
{
$validator = Validator::make($request->all(), [
'name' => 'required',
'email' => 'required|email',
'password' => 'required',
'c_password' => 'required|same:password',
//'g-recaptcha-response' => 'required|captcha',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors(), 400);
}
$name = $request->input('name');
$email = $request->input('email');
$password = $request->input('password');
$user = User::where('email', $email)->first();
if ($user) {
return $this->sendError('This email address is already taken. Please try another.', [], 400);
}
$user = User::create([
'name' => $name,
'email' => $email,
'password' => bcrypt($password)
]);
$user->sendApiEmailVerificationNotification();
return $this->sendResponse([], 'Please confirm yourself by clicking on verify user button sent to you on your email.');
}
/**
* Send reset password email API
* #param Request
* #return \Illuminate\Http\Response
*/
public function sendPasswordResetLink(Request $request)
{
$validator = Validator::make($request->all(), [
'email' => 'required|email',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors(), 400);
}
$email = $request->input('email');
$response = Password::sendResetLink(['email' => $email], function (Message $message) {
$message->subject($this->getEmailSubject());
});
switch ($response) {
case Password::RESET_LINK_SENT:
return $this->sendResponse([], 'We have e-mailed your password reset link!');
case Password::INVALID_USER:
return $this->sendError('We can\'t find a user with that e-mail address.', [], 400);
}
}
/**
* Reset password action API
* #param Request
* #return \Illuminate\Http\Response
*/
public function callResetPassword(Request $request)
{
$validator = Validator::make($request->all(), [
'token' => 'required',
'email' => 'required|email',
'password' => 'required',
'password_confirmation' => 'required|same:password',
]);
if ($validator->fails()) {
return $this->sendError('Validation Error.', $validator->errors(), 400);
}
// Here we will attempt to reset the user's password. If it is successful we
// will update the password on an actual user model and persist it to the
// database. Otherwise we will parse the error and return the response.
$response = $this->broker()->reset(
$this->credentials($request),
function ($user, $password) {
$this->resetPassword($user, $password);
}
);
if ($response == Password::PASSWORD_RESET) {
return $this->sendResponse([], 'User password has been successfully reset.');
} else {
return $this->sendError($response, [], 400);
}
}
/**
* Logout API
* #param Request
* #return \Illuminate\Http\Response
*/
public function logout(Request $request)
{
if (Auth::check()) {
Auth::user()->oauthAcessTokens()->delete();
return $this->sendResponse([], 'User logged out successfully.');
}
}
}
Base Controller
<?php
namespace App\Http\Controllers\Api;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
class BaseController extends Controller
{
/**
* success response method.
*
* #return \Illuminate\Http\Response
*/
public function sendResponse($result, $message = null)
{
$response = [
'success' => true,
'data' => $result
];
if (!empty($message)) {
$response['message'] = $message;
}
return response()->json($response, 200);
}
/**
* return error response.
*
* #return \Illuminate\Http\Response
*/
public function sendError($error, $errorMessages = [], $code = 422)
{
$response = [
'success' => false,
'message' => $error,
];
if (!empty($errorMessages)) {
$response['data'] = $errorMessages;
}
return response()->json($response, $code);
}
}

how to create a token in laravel tymons/jwt-auth

I want to create a token encoded with user role. I have tried with seeing the documentation, But I am not getting a token. what I have tried.
I am using laravel 5.8 and package version "tymon/jwt-auth": "^1.0.0-rc.2"
Thank you
AuthController
public function login()
{
$credentials = request(['email', 'password']);
if (! $token = auth()->guard('api')->attempt($credentials)) {
return response()->json(['errors' => 'In-valid username and Password'], 401);
}
$customClaims =[
'role' => auth('api')->user()->getRoleNames()
];
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload);
return $this->respondWithToken($token);
}
protected function respondWithToken($token)
{
return response()->json([
'success' => true,
'access_token' => $token,
'token_type' => 'bearer',
]);
}
Based on the documentation, you might need to do attempt() twice, like this:
public function login()
{
$credentials = request(['email', 'password']);
if (!auth()->guard('api')->claims(['role' => 'bar'])->attempt($credentials)) {
return response()->json(['errors' => 'In-valid username and Password'], 401);
}
$token = auth('api')->claims(['role' => auth('api')->user()->getRoleNames()])->attempt($credentials);
return $this->respondWithToken($token);
}
Your User MOdel should like this
class User extends Authenticatable implements JWTSubject
{
use Notifiable, HasRoles;
public function getJWTIdentifier()
{
return $this->getKey();
}
public function getJWTCustomClaims()
{
return [];
}
}
public function login()
{
$credentials = request(['email', 'password']);
if (!$token = JWTAuth::attempt($credentials)) {
return response()->json(['errors' => 'In-valid username and Password'], 401);
}
$customClaims =[
'role' => auth('api')->user()->getRoleNames()
];
$payload = JWTFactory::make($customClaims);
$token = JWTAuth::encode($payload);
return $this->respondWithToken($token);
}
Try This
use JWTAuth;
use Tymon\JWTAuth\Exceptions\JWTException;
class AuthenticateController extends Controller
{
public function login(Request $request)
{
// grab credentials from the request
$credentials = $request->only('email', 'password');
try {
// attempt to verify the credentials and create a token for the user
if (!auth()->guard('api')->claims(['role' => 'bar'])->attempt($credentials))
{
return response()->json(['errors' => 'In-valid username and Password'], 401);
}
$token = auth('api')->claims(['role' => auth('api')->user()->getRoleNames()])->attempt($credentials);
return $this->respondWithToken($token);
} catch (JWTException $e) {
// something went wrong whilst attempting to encode the token
return response()->json(['error' => 'could_not_create_token'], 500);
}
// all good so return the token
return response()->json(compact('token'));
}
}

controller method return value without jwt token

I have configured Jwt/tymon API authentication and use custom model, what I want is controller function should not be accessed without the token generated by JWT on login,
Route
Route::group([
'middleware' => 'api'
// 'prefix' => 'auth'
], function ($router) {
Route::post('auth/mpalogin', 'MpaLoginController#mpaLogin')->name('login');
Route::post('auth/mpalogout', 'MpaLoginController#logout');
Route::post('auth/mparefresh', 'MpaLoginController#refresh');
Route::post('auth/mpame', 'MpaLoginController#myinfo');
Route::post('auth/mpag', 'MpaLoginController#awain');
});
CONTROLLER -> The awain method at the last is accessed without sending the token, which I don't want, I want every method that I create in this controller should be accessed only by token
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Requests;
use Config;
use JWTAuth;
use JWTAuthException;
use App\Mpa;
class MpaLoginController extends Controller
{
public function __construct()
{
Config::set('jwt.user', Mpa::class);
Config::set('auth.providers', ['users' => [
'driver' => 'eloquent',
'model' => Mpa::class,
]]);
$this->middleware('auth', ['except' => ['mpaLogin']]);
}
public function mpaLogin(Request $request){
$credentials = $request->only('email', 'password');
$token = null;
try {
if (!$token = auth()->attempt($credentials)) {
return response()->json([
'response' => 'error',
'message' => 'invalid_email_or_password',
]);
}
} catch (JWTAuthException $e) {
return response()->json([
'response' => 'error',
'message' => 'failed_to_create_token',
]);
}
return response()->json([
'response' => 'success',
'result' => [
'token' => $token,
'message' => 'I am front mpa',
],
]);
}
/**
* Get the authenticated User.
*
* #return \Illuminate\Http\JsonResponse
*/
public function myinfo()
{
return response()->json(auth()->user());
}
/**
* Log the user out (Invalidate the token).
*
* #return \Illuminate\Http\JsonResponse
*/
public function logout()
{
auth()->logout();
return response()->json(['message' => 'Mpa Successfully logged out']);
}
/**
* Refresh a token.
*
* #return \Illuminate\Http\JsonResponse
*/
public function refresh()
{
return $this->respondWithToken(auth()->refresh());
}
/**
* Get the token array structure.
*
* #param string $token
*
* #return \Illuminate\Http\JsonResponse
*/
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'bearer',
'expires_in' => auth()->factory()->getTTL() * 60
]);
}
public function awain()
{
return response()->json("xyz");
}
}
You can try this way.
Add this middleware file in your App\Http\Middleware folder.
Filename must be JWTMiddleware.php
<?php
namespace App\Http\Middleware;
use Closure;
use App\Models\Authentication\Auth;
use Tymon\JWTAuth\Facades\JWTAuth;
use Tymon\JWTAuth\Exceptions\TokenExpiredException;
use Tymon\JWTAuth\Exceptions\TokenInvalidException;
use Tymon\JWTAuth\Exceptions\JWTException;
class JWTMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
if (is_null($request->bearerToken())) {
return response()->json(['error' => 'Token required.'], 401);
}
try {
// attempt to verify the credentials and create a token for the user
$token = JWTAuth::getToken();
$apy = JWTAuth::getPayload($token)->toArray();
} catch (TokenExpiredException $e) {
return response()->json(['error' => 'Session Expired.', 'status_code' => 401], 401);
} catch (TokenInvalidException $e) {
return response()->json(['error' => 'Token invalid.', 'status_code' => 401], 401);
} catch (JWTException $e) {
return response()->json(['token_absent' => $e->getMessage()], 401);
}
return $next($request);
}
}
register this middleware in $routeMiddleware of App\Http\kernel.php file.
protected $routeMiddleware = [
....
....
'jwt' => \App\Http\Middleware\JWTMiddleware::class,
];
Add this middleware to your Route group.
Route::group(['middleware' => [ 'jwt', 'jwt.auth']], function () {
....
....
});
Working example Repo:
https://github.com/kennethtomagan/laravel-5-api-boilerplate/
Replace
$this->middleware('auth', ['except' => ['mpaLogin']]);
With this
$this->middleware('api', ['except' => ['mpaLogin']]);
Also remove the middleware from the route group. As you are adding the middleware code in the construct of the controller.

Login throttles in laravel 5.1 with ajax

I'm working on a login form which uses ajax and I can't setup login throttling.
ThrottlesLogins trait redirects somewhere but I don't need that. How can I return number of seconds when user fails password n times?
Controller:
<?php
namespace App\Http\Controllers\Login;
use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Illuminate\Foundation\Auth\ThrottlesLogins;
use Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
use Auth;
class LoginController extends Controller
{
use AuthenticatesAndRegistersUsers, ThrottlesLogins;
public function index()
{
if (Auth::check()) return redirect(url('/dashboard'));
else return view('admin.login');
}
public function login(Request $request) {
$this->validate($request, [
'username' => 'required', 'password' => 'required',
]);
$credentials = $request->only('username', 'password');
$throttles = $this->isUsingThrottlesLoginsTrait();
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
if (Auth::attempt($credentials, $request->has('remember')))
{
return $this->handleUserWasAuthenticated($request, $throttles);
//return response()->json(['code' => 1, 'redirect' => url('/dashboard')]);
}
//else return response()->json(['code' => 0]);
if ($throttles) {
$this->incrementLoginAttempts($request);
}
}
}
routes.php
/* Login */
Route::group(array('prefix' => 'login', 'namespace' => 'Login', 'middleware' => 'guest'), function() {
Route::get('/', 'LoginController#index');
Route::post('/', 'LoginController#login');
});
You can change:
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
return $this->sendLockoutResponse($request);
}
into
if ($throttles && $this->hasTooManyLoginAttempts($request)) {
if ($request->ajax()) {
return response()->json(['lockout_time' => $this->lockoutTime()]);
}
else {
return $this->sendLockoutResponse($request);
}
}

Resources