Modify Laravel API Unauthenticated Message

When building API that requires authentication to access the resource in laravel.

You get "unauthenticated" as response and code of 401. The illustrattion below is an example of the message you get.

{"message" : "Unauthenticated."}

I find it quite not well detailed, we need to formate the message in a much better way for who ever will be consuming it to be able to work with the response.

This can easily be modified by adding a custom or editing the unauthenticated method to app/Exceptions/Handler.php:

 /**
     * Convert an authentication exception into an unauthenticated response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Auth\AuthenticationException  $exception
     * @return \Illuminate\Http\Response
     */
    protected function unauthenticated($request, AuthenticationException $exception)
    {
        if ($request->expectsJson()) {
            return response()->json(['status' => false, 'message' => 'Unauthenticated, kindly 
                                                                                                                           login'], 401);
        }

        return redirect()->guest(route('login'));
    }

First we check if the request is expecting a json response. If that is true, then we can return the response in the if statement else the user will be redirected to the login page.

With the status attached, whoever is consuming the api, can easily check if the authentication status is true or false.

You can format to your own taste.

If you find this helpful, kindly drop a comment or an emoji, cheers.