Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Haseeb69's avatar

Custom Message for Unauthorized api call in laravel 8

im trying to return a message on an api call if user is not Authenticated

All solutions i saw were of old laravel versions which does not seem to work with laravel 8

this is default middleware/Authenticate.php file

    protected function redirectTo($request)
    {
        if (!$request->expectsJson()) {
            return route("login");
        }
    }

i dont have a login view or anything so if i change it to

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

i get Warning Header May Not Contain More Than A Single Header New Line

any help will be appreciated Note: handle function does not work in this particular middleware

0 likes
13 replies
CorvS's avatar

im trying to return a message on an api call if user is not Authenticated

By default a 401 response with { "message": "Unauthenticated"} is returned for API requests (or rather requests that expect a JSON response).

You want to change that message or what exactly is it you are trying to achieve? You could simply override the unauthenticated() method inside your Authenticate middleware.

Haseeb69's avatar

right now if im not authenticated i get a 404 message with page not found error so i wanted to return any message that is is unauthorized im not getting a default unauthorized message

CorvS's avatar

If you keep the redirectTo as shown in your first code block and your request expects JSON you should get the response I mentioned. If that's not the case please check if you override any other methods from Illuminate\Auth\Middleware\Authenticate inside your Authenticate middleware.

Haseeb69's avatar

nope bro it doesnt work if it did i wouldn't try to change it

CorvS's avatar

Are you sure your request expects JSON then? Did you check the header if Content-Type: application/json is set?

1 like
Haseeb69's avatar

oh so this was the issue i was using postman for testing purposes and i used the default Accept : * when i changed it to Accept: application/json im finally getting unauthenticated error anyways thanks for help

mvd's avatar
mvd
Best Answer
Level 48

Hi @haseeb69

redirectTo expects a path.

You can add the method unauthenticated in your middleware/Authenticate.php file

 protected function unauthenticated($request, array $guards)
    {
        abort(response()->json(['error' => 'Unauthenticated.'], 401));
    }
11 likes
CorvS's avatar

That reply doesn't even make sense, but mark it as best answer. Well done.

juanma386's avatar

@mvd Thank you very much, it has been pleasantly functional the function you have given me, of course I am grateful to the whole community for their collaboration. Laravel unlike other Frameworks is more worked and is very friendly to us developers. Greetings from Posadas, Argentina.

gr_nunari's avatar

It will handle API as well as basic auth. final function unauthenticated($request, array $guards): void {

    if(request()->hasHeader('Authorization') || $request->is('api/*')){
        abort(response()->json(
            [
                'status' => 'Error',
                'message' => 'Unauthenticated',
                'data' => []
            ], 401));
    }

    Parent::unauthenticated($request, $guards);

}
jrburningham's avatar

This is late, but there is a very easy way to update the message that's essentially a copy of what the Parent does, just using your own custom message.

//Within Middleware/Authenticate.php add the following
protected function unauthenticated($request, array $guards): void {
        throw new AuthenticationException(
            __('auth.unathenticated-message'), //<-- This is where you add your message
            $guards,
            $this->redirectTo($request)
        );
}

Please or to participate in this conversation.