John Davidson

php - laravel reponse json message not translated

0 comments
Message:


I am using laravel 8 with sanctum api (vue 3 spa).


I have never used localization before....and for this app I need that.


I created a middleware SetLocale with this content


public function handle($request, Closure $next)
{
app()->setLocale(config('app.locale'));
if(session()->has('locale')) {
app()->setLocale(session('locale'));
}

return $next($request);
}

and registered in both web and api (app/Http/Kernel.php) @middlewareGroups


From the login form there is a select that change locale and make a post request to server to change the locale


Session()->put('locale', $request->input('locale'));
app()->setLocale(session('locale'));

return response()->json(['locale' => app()->currentLocale()]);

In the login form the server validation responds with the locale messages.... but the problem is the customized message (Customize laravel sanctum unauthorize response) it is not translated - it gives me in 'en' ... even if the locale is 'de'


$this->renderable(function (\Illuminate\Auth\AuthenticationException $e, $request) {
if ($request->is('api/*')) {
return response()->json([
'message' => trans('_custom.not_authenticated')
], 401);
}
});

The file is there for every language _custom.php (resources/lang/de, resources/lang/en, etc )


example for _custom.php "de":


<?php

return [
'not_authenticated' => 'Nicht berechtigt'
];

The message is still in en ... but if press login (without changing anything) .... the validation errors are in 'de'


Why ? What I missed ?


Could be that the message is returned before the middleware runs ?


*** UPDATE 1 ***


It seems to work partially using in request Accept Language header .... but there is another problem.


In vue I have this approach for the axios:


const api = axios.create({
withCredentials: true,
headers: {
common: {
'Accept-Language': document.documentElement.lang
}
}
});

export default api;

In the vue app when changing the language .... I also update the document.documentElement.lang value ... but when making a request it still the default value 'en'


Is there any way I can change dynamic the value for the 'Accept-Language' header instead of adding for each request the header ?



My Answer:
> setLocale($request->header('Accept-Language')); return $next($request); }_

Then, in your controller or wherever you are returning the JSON response, you can use the `trans()` function to translate the message. For example:

php
return response()->json([
'message' => trans('messages.success'),
]);


Make sure you have the translation file set up in your `resources/lang` directory with the appropriate translations.

Rate this post

3 of 5 based on 7060 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us