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

umefarooq's avatar

Hi, just added some more functionality to the script, right now this script adding locales all routes, if you want to skip locales for some routes like admin or private i have created pull request for this here is link for pull request

https://github.com/Marwelln/laravel-multiple-locales/pull/4

How you can skip locales

First Step

download my repo code, if my request is not pulled in original repo.

https://github.com/umefarooq/laravel-multiple-locales

2nd Step

open config/app.php find skip_locales or add config than add first segment of url you want to skip like following

 'skip_locales' => ['admin','other'] 

now you can call URL with and without locales

www.yoursite.com/admin //without locale

and 

www.yoursite.com/en/page-slug //with locale
freel's avatar

Hello,

I have issue, seems that validation is not working with this solution, and locale after login goes to default locale. maybe some one could give me some tips how to solve this issue. By the way I am using laravel 5.2 Thx

freel's avatar

Solved problem with validation. Changed middleware to:

\App\Http\Middleware\Language::class, \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

as well changed routes. redirect to url changed to route name

Ro9e's avatar

Hi all,

using this example whit phpunit i found that RouteServiceProvider doesn't load the correct route because, request parameter, the segments are null when make a request as 'http://localhost/locale/path'. The request object passed as parameter is not the current request.

what is the problem?

Thanks

Regards

muhammad.atallah's avatar

Hi all

I looking to change the direction from ltr To rtl in Arabic for example .

I think to modify the CSS based upon the Session language direction or make two separates design and swap between them.

I need the advice to achieve that by the best way according to this wonderful example

Thanks.

freel's avatar

seems that is not working with new new laravel version properly. issue is with auth. Anyone have idea how to fix this.

freel's avatar

On newest version no. Bit older yes. I am talking about laravel 5.2

ilmoralito's avatar

Using Laravel 5.2 Getting Interface 'App\Http\Middleware\Middleware' not found error in Language.php

subhendugiri's avatar

Nice example but struggled a couple of days to implement for using default authentication method provided by laravel 5. Apart from that I have some routing which does not require localization. So I modified the above example a little bit.

Please see my answer at http://stackoverflow.com/questions/29279977/laravel-5-multilanguage-support/39384200#39384200.

Step 1: Add your locales In config/app.php add skip_locals line below locales

'locales' => ['en' => 'English', 'sv' => 'Swedish'],

'skip_locales' => ['admin','auth','etc'],

Step 2: Prefix your routes change the map method to the following

public function map(Router $router, Request $request)
{
    $locale = $request->segment(1);
    $this->app->setLocale($locale);
    $skip_locales= $this->app->config->get('app.skip_locales');  

    // If the locale is added to to skip_locales array continue without locale
    if (in_array($locale, $skip_locales)) {
        $router->group(['namespace' => $this->namespace], function($router)
        {
            require app_path('Http/routes.php');
        });
    }
    else {
        $router->group(['namespace' => $this->namespace, 'prefix' => $locale], function($router) {
            require app_path('Http/routes.php');
        });
    }
}

Step 3: Create a language middleware Change the contents with this one

namespace App\Http\Middleware;

use Closure;
use Illuminate\Routing\Redirector;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
use Illuminate\Contracts\Routing\Middleware;

class Language implements Middleware
{

    public function __construct(Application $app, Redirector $redirector, Request $request)
    {
        $this->app = $app;
        $this->redirector = $redirector;
        $this->request = $request;
    }

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request            
     * @param \Closure $next            
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // Make sure the current local exists
        $locale = $request->segment(1);

        // If the locale is added to to skip_locales array continue without locale
        if (in_array($locale, $this->app->config->get('app.skip_locales'))) {
            return $next($request);
        } else {
            // If the locale does not exist in the locales array continue with the fallback_locale
            if (! array_key_exists($locale, $this->app->config->get('app.locales'))) {
                $segments = $request->segments();
                array_unshift($segments, $this->app->config->get('app.fallback_locale'));
                // $segments[0] = $this->app->config->get('app.fallback_locale');
                return $this->redirector->to(implode('/', $segments));
            }
        }
        $this->app->setLocale($locale);

        return $next($request);
    }

}

Hope this will help!

da_n's avatar

I found this was breaking PHPUnit as well, I found adding this to the TestCast.php setUp method allowed the tests to run:

// Set locale for PHPUnit instance
    $this->app->setLocale('en');

Note I had to combine several of the provided responses on this thread to get a properly working implementation, as there were a couple of minor issues, but want to thank everybody for their solutions. Hope this helps someone.

Edit: I should note this obviously hardcodes a language locale to your tests, however you can do further tests and override the hardcoded value to check for any issues with different locales e.g.:

/** @test */
public function app_locale_is_set_to_de()
{
    $this->app->setLocale('de');

    $this->assertEquals(
        'de',
        $this->app->getLocale()
    );
} 
rexeh's avatar

Perhaps a bad solution, but a really simple way to do this (without breaking all your links) is to just set it in the session?

I've simply attached Middleware to my route groups with this simple bit of code.

 public function handle($request, Closure $next)
{

    App::setLocale($request->session()->get('language', function() {
        return Config::get('app.locale');
    }));

    return $next($request);
}

And then give users the options of clicking various flags (or choosing from a dropdown of available languages) which sets the correct locale in the session.

If I wanted to persist it for logged in users, then would simply extend my user model to store on their account and autoload if they're authed and a preference exists.

That way I can choose to translate which route groups I want... for example not my API endpoints or admin systems.

LTroya's avatar

A little tweak to handle method. If the url is /samples, it will be replaced by $segments[0] = 'en'. The current method will return /en instead of /en/samples.

public function handle($request, Closure $next)
    {
        $locale = $request->segment(1);

        if (! array_key_exists($locale, $this->app->config->get('app.locales'))) {
            $defaultLocale = $this->app->config->get('app.fallback_locale');
            $segments = collect($request->segments())->prepend($defaultLocale);

            return $this->redirector->to(
                $segments->implode('/')
            );
        }

        $this->app->setLocale($locale);

        return $next($request);
    }

This will transform /samples into /en/samples.

1 like
Previous

Please or to participate in this conversation.