DEV Community

David Carr
David Carr

Posted on • Originally published at dcblog.dev on

Laravel API change unauthenticated message

When making API calls to Laravel when a user who is not authenticated makes a call a 401 status code is returned and the following response:

{"message":"Unauthenticated."}
Enter fullscreen mode Exit fullscreen mode

Which I find a little strange it's an error so message should say error in my opinion.

This can easily be changed by adding a customer unauthenticated method to app/Exceptions/Handler.php :

protected function unauthenticated($request, AuthenticationException $exception) 
{
    if ($request->expectsJson()) {
        return response()->json(['error' => 'Unauthenticated.'], 401);
    }

    return redirect()->guest('login');
}
Enter fullscreen mode Exit fullscreen mode

Now the response will say error instead of message.

Top comments (2)

Collapse
 
viraljetani profile image
Viral Jetani

Hey there,

Looks like this isn't working anymore with the latest versions of laravel.

Collapse
 
viraljetani profile image
Viral Jetani

Sorry, It actually is working, I just had to import the AuthenticationException class on the top.

Thanks for the article.
Cheers!