It seems like the issue is with the redirection happening before the JSON response is returned. To prevent this, you can modify the app/Http/Middleware/Authenticate.php file to return a JSON response instead of redirecting.
Here's an example of how you can modify the handle method in Authenticate.php:
public function handle($request, Closure $next, ...$guards)
{
if ($this->authenticate($request, $guards) === 'authentication_failed') {
return response()->json([
'errors' => [
'status' => 401,
'message' => 'Unauthenticated',
],
], 401);
}
return $next($request);
}
This will return a JSON response with a 401 status code if the user is not authenticated. Make sure to import the Closure class at the top of the file.
Also, make sure to remove the unauthenticated method from your Handler.php file as it is no longer needed.
With these changes, you should be able to get a JSON response for unauthenticated users.