skip to Main Content

I’m localizing validation error messages at the moment. I was trying to do it according to this article. There are no errors displayed, even though the article was published a long time ago, and Laravel 5 is used there, but the validation messages are still in English even when I pass a different locale to the request that switches languages. But when I change the locale in the app config (config/app.php) to ‘ru’, the messages are displayed in Russian. I don’t understand what I am doing wrong. Here is the GitHub repo of this project, if you need it.

LanguageController.php:

<?php

namespace AppHttpControllers;

use AppHttpRequests;
use IlluminateSupportFacadesConfig;
use IlluminateHttpRequest;
use IlluminateSupportFacadesRedirect;
use IlluminateSupportFacadesSession;

class LanguageController extends Controller
{
    public function switchLang(Request $request)
    {
        if (array_key_exists($request->userLocale, Config::get('languages'))) {
            Session::put('locale', $request->userLocale);
        } else {
            Session::put('locale', Config::get('app.fallback_locale'));
        }
        return Redirect::back();
    }
}

config/languages.php (I created this file):

<?php
return [
    'en' => 'English',
    'ru' => 'Русский',
];

My route:

Route::post("setLocale", [LanguageController::class, "switchLang"]);

Language.php middleware:

<?php

namespace AppHttpMiddleware;

use Closure;
use IlluminateHttpRequest;
use IlluminateSupportFacadesApp;
use IlluminateSupportFacadesConfig;
use IlluminateSupportFacadesSession;

class Language
{
    /**
     * Handle an incoming request.
     *
     * @param  IlluminateHttpRequest  $request
     * @param  Closure(IlluminateHttpRequest): (IlluminateHttpResponse|IlluminateHttpRedirectResponse)  $next
     * @return IlluminateHttpResponse|IlluminateHttpRedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        if (
            Session::has('locale') &&
            array_key_exists(
                Session::get('locale'),
                Config::get('languages')
            )
        ) {
            App::setLocale(Session::get('locale'));
        } else {
            App::setLocale(Config::get('app.fallback_locale'));
        }
        return $next($request);
    }
}

Kernel.php:

protected $middlewareGroups = [
    // ...
    'api' => [
        // LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class,
        'throttle:api',
        AppHttpMiddlewareLanguage::class,
        IlluminateRoutingMiddlewareSubstituteBindings::class,
    ],
];

Help is greatly appreciated. Thanks in advance! If you need something else to understand my question, feel free to ask!

3

Answers


  1. Chosen as BEST ANSWER

    The problem was that I use sessions, and Laravel API default setup doesn't include them. So, what did I do? I've added IlluminateSessionMiddlewareStartSession::class to the api middleware group, just as @r1v3n said here, and it worked! Now I can switch locales. Thank you, everyone, and especially @paul-k, for leading me to this answer!


  2. You need to debug to understand where the problem is happening. Start by checking if the user has locale in his session. You can do that from the browser or by debugging Language middleware using xdebug() or dd() function.

    Login or Signup to reply.
  3. Actually, Laravel has introduced a way to deal with this problem. Even in Laravel 5 there is localization. What you need is to change your views a bit.
    First of all you need to use keys.

    For example, instead of using this:

    <span>Login page</span>
    

    You need to use this in your .blade file:

    <span>__('pages.login.title')</span>
    

    And then define this key in your ./resources/lang/{en or ru}.php language file as key and value. I put an example below:

    <?php
    return [
        'pages.login.title' => 'Login page'
    ];
    

    Then, when you want to set locale for a user, it is better to store it as a column in users table (it’s better even for getting statistics!). Then in boot method of your ./app/Providers/AppServiceProvider.php add this code:

    if (auth()->check()) {
        App::setLocale(auth()->user()->locale)
    }
    

    And at last, I wanna mention that the locale you give to App::setLocale() method should be the same as your lang file in ./resources/lang directory.

    Also, you can read more in Laravel 9 documentation as your project uses Laravel 9.

    Laravel 9 localization.

    I hope I could help you in your journey 🙂 <3

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search