I have tried several tutorials in the internet but it doesn’t work or the language not changing, I already stored the translation into lang
directory, and the session is already set Localization Session
here is my source code:
This is my controller :
class LocalizationController extends Controller
{
public function setLang($locale)
{
App::setLocale($locale);
Session::put("locale", $locale);
return redirect()->back();
}
}
This is my Middleware :
class LocalizationMiddleware
{
/**
* Handle an incoming request.
*
* @param Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse) $next
*/
public function handle(Request $request, Closure $next): Response
{
if (Session::get("locale") != null) {
App::setLocale(Session::get("locale"));
} else {
Session::put("locale", "en");
App::setLocale(Session::get("locale"));
}
return $next($request);
}
}
This is the route :
Route::get("locale/{lang}", [LocalizationController::class, 'setLang']);
Language Switcher :
<a href="{{ url('locale/id') }}"><img class="h-5 mt-4" src="{{ asset('images/flag/id_flag.png') }}"
alt=""></a>
<a href="{{ url('locale/en') }}"><img class="h-5 mt-4" src="{{ asset('images/flag/uk_flag.png') }}"
alt=""></a>
Translated Element :
<h1 class="font-black lg:text-5xl md:text-4xl text-3xl md:w-[500px] mx-auto">{{ __('home.hero.header') }}</h1>
I have tried several tutorials in the internet, please help.
2
Answers
I already solve the problem, I put the middleware classes
AppHttpMiddlewareLocalizationMiddleware::class,
into the wrong middleware kernel group.Wrong kernel group :
Group that i should put the middleware:
Check Language Files: Make sure you have the necessary language files in the resources/lang directory for each supported language. For example, you should have en and id directories with language files like messages.php inside them.
Namespace in Language Files: Ensure that the translations in your language files use the correct namespace. The key in your translation file should match the one you’re using in your view:
For example, if your view has:
Then your resources/lang/en/messages.php file should have:
Clear Cache: If you’ve made changes to your language files or configuration, clear the cache to ensure the changes take effect.
php artisan cache:clear