hretic
hretic

Reputation: 1075

changing Unauthenticated message

when i ajax call a route with auth middleware i get (while not logged in)

{"message":"Unauthenticated."}

i want to change this to something like

{"stat" : 'er' , 'msg' : 'Unauthenticated' }

it seems to be somewhere deep inside vendor ... how can i have this message outside vendor and change it ?

i have to add some extra text to able to post the question so here it is apparently its too short : some text some text some text some text some text some text some text some text some text some text some text

Upvotes: 4

Views: 1112

Answers (2)

Codeparl
Codeparl

Reputation: 326

This is how I did mine by adding $this->renderable(...) before $this->reportable(...) in the register method within the Handler class for Laravel 9:

<?php

namespace App\Exceptions;

  use Illuminate\Auth\AuthenticationException;
 use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
 use Throwable;

 class Handler extends ExceptionHandler
{
/**
 * A list of exception types with their corresponding custom log levels.
 *
 * @var array<class-string<\Throwable>, \Psr\Log\LogLevel::*>
 */
protected $levels = [
    //
];

/**
 * A list of the exception types that are not reported.
 *
 * @var array<int, class-string<\Throwable>>
 */
protected $dontReport = [
    //
];

/**
 * A list of the inputs that are never flashed to the session on validation exceptions.
 *
 * @var array<int, string>
 */
protected $dontFlash = [
    'current_password',
    'password',
    'password_confirmation',
];

/**
 * Register the exception handling callbacks for the application.
 *
 * @return void
 */
public function register()
{

    $this->renderable(function (AuthenticationException $e, $request) {
         return response()->json([ 'message' => __('auth.unauthenticated') ], 401);
         });

        $this->reportable(function (Throwable $e) {

    });
}

}

Upvotes: 0

Mohammed Aktaa
Mohammed Aktaa

Reputation: 1353

No not inside vendor you need to go to Handler Class in App\Exceptions and in render function put this before return:

     if ($request->expectsJson() && $exception instanceof AuthenticationException)
        return response()->json(["stat" => 'er' , 'msg' => 'Unauthenticated' ], 401);

Upvotes: 4

Related Questions