From 6f3aa7a4c5d153a187a0aef7c6cb2d2d7aa9dd12 Mon Sep 17 00:00:00 2001 From: Dries Vints Date: Fri, 12 Oct 2018 15:40:15 +0200 Subject: [PATCH] Don't redirect for api calls When calling api routes the Authenticate middleware attempts to redirect you to the login page. If you expect JSON back or don't have auth routes then you don't want this to happen. By re-using the logic from Laravel's exception handler on which format to output we can also determine wether to redirect the user to the login page or give them a JSON error response. --- app/Http/Middleware/Authenticate.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/app/Http/Middleware/Authenticate.php b/app/Http/Middleware/Authenticate.php index 41ad4a90..a4be5c58 100644 --- a/app/Http/Middleware/Authenticate.php +++ b/app/Http/Middleware/Authenticate.php @@ -14,6 +14,8 @@ class Authenticate extends Middleware */ protected function redirectTo($request) { - return route('login'); + if (! $request->expectsJson()) { + return route('login'); + } } }