JerryBels
1 month ago
445
1
Laravel

Localize app with jetstream

Posted 1 month ago by JerryBels

Hello,

I'm trying to start a project with jetstream, on Laravel 8, while handling multiple languages. All views in Jetstream are already set to be translated - so it's fine here. But how would you go about letting the user choose his language?

My first idea was to go like mylaravel.com/en/somepage. I tried to implement it using https://github.com/mcamara/laravel-localization but it won't work with jetstream - or at least I didn't successfully make it work. I didn't find how I could force jetstream (and fortify) to take a prefix and set the language according to it. My experiment about this after some suggestions from a user on SO got like this. I tried to add a middleware to handle setting the locale. Added :

Fortify.php :

    'path' => '{lang}',
    'middleware' => ['web', 'setLang']

new middleware setLang :

class SetLang {
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle(\Illuminate\Http\Request $request, Closure $next) {
        // $lang = 'en';
        // $request->attributes->add(['lang' => 'en']);
        $request->route()->setParameter('lang', 'en');
        // $request->request->set('lang', 'en');

        return $next($request);
    }
}

Added the middleware to $routeMiddleware.

I'm receiving this error when trying to reach http://mylaravel/en/login :

ErrorException
Missing required parameters for [Route: login] [URI: {lang}/login]. (View: /var/www/resources/views/auth/login.blade.php)

So I saved this experiment on a branch and got back to my previous commit, without https://github.com/mcamara/laravel-localization. I had an idea I wanted to explore, and I found something very close to it here : https://learninglaravel.net/forum/laraveltutorials/how-to-use-multiple-languages-in-your-laravel-5-website

i tried to implement it but now everything is returning a 404... Is it a difference between Laravel 5 and 8?

Another approach I'm yet to try would be to have a specific button dedicated to set the language on the website, without using the url at all, and trying to set the default language if the user never chose one by detecting the browser language. Saving this to session and cookies I guess.

What do you think?

Please sign in or create an account to participate in this conversation.