Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

yelnya's avatar

How to switch language with routes?

hi, I am using : dimsav/laravel-translatable

and I am not sure how to create a panel where I can choose & switch between language like 'Fr' and 'Eng'

from the demo of the package, language can be changed with: App::setLocale('en');

and the current locale can be obtained with: App::getLocale();

can someone show me a simple example of how the route/view/controller look like?

thank you

0 likes
3 replies
jekinney's avatar

It's not necessarily that simple. What I mean is you need to persist the user's selection. If you refreshed the page it would go to the default.

Otherwise just set up post route. A translation controller. If you're not strictly using rest, a toggleLanguage method. Looking for the language in the URL or body. Simply call your packages method to set the language. Store the requested language type in the session or cache. Then return back().

Now I suggest a middleware to check every applicable request. If session or cache has the language set, return the language. If not what ever default setting.

Other then persistent, it's extremely basic, not sure a tutorial is needed. If so you may need to watch some fundamental videos here.

yelnya's avatar

I followed the method used in:


https://laracasts.com/discuss/channels/tips/example-on-how-to-use-multiple-locales-in-your-laravel-5-website

with the Language Middleware handle:


    public function handle($request, Closure $next)
    {
        // Make sure current locale exists.
        $locale = $request->segment(1);

        // If provided Locale not in Available Locale Array
        if ( !in_array($locale, config('translatable.locales'))) {

            $segments = $request->segments();
            $segments[0] = config('app.fallback_locale');

            return Redirect::to(implode('/', $segments));
        }


        // Else, Set Current Locale
        App::setLocale($locale);

        return $next($request);
    }

and the people in https://laravel.io/chat said this is not the best way to make it work

quote:


All urls now have a locale segment/parameter that the url generated needs to know about. You can either specify that in every call to url() and route(), or register your values as default values. 

URL:defaults(array('locale' => $theLocale)) in your middleware to let all action()/route()/... know about this locale parameter... 

but I am not sure how and where to do that

Please or to participate in this conversation.