Custom Message for Unauthorized API call in Laravel 8 | “error”: “Unauthenticated.”

In this blog post, we learn how to change messages from unauthorized API calls in Laravel 8.

You should overwrite the method unauthenticated in your middleware/Authenticate.php file

middleware/Authenticate.php

 <?php

namespace App\Http\Middleware;

use Illuminate\Auth\Middleware\Authenticate as Middleware;

class Authenticate extends Middleware
{
    /**
     * Get the path the user should be redirected to when they are not authenticated.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return string|null
     */
    protected function redirectTo($request)
    {
        if (! $request->expectsJson()) {
            return route('login');
        }
    }

    // Add new method 
    protected function unauthenticated($request, array $guards)
    {
        abort(response()->json([
            'status' => 'false',
            'message' => 'Your Custom message',], 401));
    }
}

I hope it will help you.