laravellocalizationsanctum

How can i localize Laravel Sanctum "unauthenticated" error message?


There is a similar question, where one asked how to change the unauthenticated message (How to change laravel sanctum return "message": "Unauthenticated.").

However, I would like to localize it using my lang/en/auth.php, lang/de/auth.php files. Both contains the following records:

lang/en/auth.php:

'unauthenticated' => 'english unauthenticated.'

lang/de/auth.php:

'unauthenticated' => 'deutsch unauthenticated.'

The current language for the logged in user is stored in the session, like this: "locale";s:2:"de"; (so the current language should be german)

I have tried to modify the register method in the app/Exceptions/Handler.php:


public function register()
    {
        $this->reportable(function (Throwable $e) {
            //
        });

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

However, it seems that session is not known/ locale is not set here, since the returned message is always the default (en) one (english unauthenticated.) even though I am logged in with the german (de) language.


Solution

  • Since the question submission, I have worked with multiple Laravel projects, so I am updating the answer with some extra information for anyone in need:

    Using the __ method to translate a key is not enough on its own to handle localization in Laravel. Locale management is better handled across multiple levels, ensuring both authenticated and unauthenticated users see the correct localized content.

    Storing and Maintaining Locale:

    Session: Store the locale in the session to handle unauthenticated users:

    session()->put('locale', $locale);
    

    User (Optional): If you want the locale to persist across sessions for logged-in users, store it in the database and retrieve it as needed.

    The Critical Step: Middleware

    To properly apply the locale across your application, you need to set the locale on every request. This is where middleware comes into play. Without this step, Laravel will default to the application's base locale (typically English), which might explain why your locale wasn't being applied consistently.

    Here's an example of middleware that sets the app’s locale based on the session:

    public function handle(Request $request, Closure $next): Response
    {
        if (session()->has('locale')) {
            app()->setLocale(session()->get('locale'));
        }
    
        return $next($request);
    }
    

    Why Middleware is Important: Because HTTP is stateless, you need to set the correct locale on every single request. Moreover, users can change their locale so we need to set the language on every request.