skip to Main Content

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


  1. Chosen as BEST ANSWER

    I already solve the problem, I put the middleware classes AppHttpMiddlewareLocalizationMiddleware::class, into the wrong middleware kernel group.

    Wrong kernel group :

    protected $middleware = [
            // AppHttpMiddlewareTrustHosts::class,
            AppHttpMiddlewareTrustProxies::class,
            IlluminateHttpMiddlewareHandleCors::class,
            AppHttpMiddlewarePreventRequestsDuringMaintenance::class,
            IlluminateFoundationHttpMiddlewareValidatePostSize::class,
            AppHttpMiddlewareTrimStrings::class,
            IlluminateFoundationHttpMiddlewareConvertEmptyStringsToNull::class,
    
            // I put the middleware classes here
            // AppHttpMiddlewareLocalizationMiddleware::class,
        ];
    

    Group that i should put the middleware:

    protected $middlewareGroups = [
            'web' => [
                AppHttpMiddlewareEncryptCookies::class,
                IlluminateCookieMiddlewareAddQueuedCookiesToResponse::class,
                IlluminateSessionMiddlewareStartSession::class,
                IlluminateViewMiddlewareShareErrorsFromSession::class,
                AppHttpMiddlewareVerifyCsrfToken::class,
                IlluminateRoutingMiddlewareSubstituteBindings::class,
    
                // I should put it here
                AppHttpMiddlewareLocalizationMiddleware::class,
            ],
    

  2. 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:

    {{ __('home.hero.header') }}
    

    Then your resources/lang/en/messages.php file should have:

    'home' => [
        'hero' => [
            'header' => 'Your translated text here',
        ],
    ],
    

    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

    // Inside LocalizationController
    public function setLang($locale)
    {
        App::setLocale($locale);
        Session::put("locale", $locale);
        dd(Session::get("locale")); // Debug output
        return redirect()->back();
    }
    
    // Inside LocalizationMiddleware
    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"));
        }
        dd(Session::get("locale")); // Debug output
        return $next($request);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search