API | Laravel Framework | Tutorials

David Carr

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."}

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');
}

Now the response will say error instead of message.

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.