Easy localization for Laravel

Overview

Laravel Localization

Join the chat at https://gitter.im/mcamara/laravel-localization

Latest Stable Version Total Downloads Build Status Open Source Helpers Reviewed by Hound

Easy i18n localization for Laravel, an useful tool to combine with Laravel localization classes.

The package offers the following:

  • Detect language from browser
  • Smart redirects (Save locale in session/cookie)
  • Smart routing (Define your routes only once, no matter how many languages you use)
  • Translatable Routes
  • Supports caching & testing
  • Option to hide default locale in url
  • Many snippets and helpers (like language selector)

Table of Contents

Laravel compatibility

Laravel laravel-localization
4.0.x 0.13.x
4.1.x 0.13.x
4.2.x 0.15.x
5.0.x/5.1.x 1.0.x
5.2.x-5.4.x (PHP 7 not required) 1.2.x
5.2.x-5.8.x (PHP 7 required) 1.3.x
5.2.0-6.x (PHP 7 required) 1.4.x
5.2.0-8.x (PHP 7 required) 1.6.x

Installation

Install the package via composer: composer require mcamara/laravel-localization

For Laravel 5.4 and below it necessary to register the service provider.

Config Files

In order to edit the default configuration you may execute:

php artisan vendor:publish --provider="Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider"

After that, config/laravellocalization.php will be created.

The configuration options are:

  • supportedLocales Languages of your app (Default: English & Spanish).
  • useAcceptLanguageHeader If true, then automatically detect language from browser.
  • hideDefaultLocaleInURL If true, then do not show default locale in url.
  • localesOrder Sort languages in custom order.
  • localesMapping Rename url locales.
  • utf8suffix Allow changing utf8suffix for CentOS etc.
  • urlsIgnored Ignore specific urls.

Register Middleware

You may register the package middleware in the app/Http/Kernel.php file:

<?php namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel {
    /**
    * The application's route middleware.
    *
    * @var array
    */
    protected $routeMiddleware = [
        /**** OTHER MIDDLEWARE ****/
        'localize'                => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRoutes::class,
        'localizationRedirect'    => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
        'localeSessionRedirect'   => \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
        'localeCookieRedirect'    => \Mcamara\LaravelLocalization\Middleware\LocaleCookieRedirect::class,
        'localeViewPath'          => \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationViewPath::class
    ];
}

Usage

Add the following to your routes file:

// routes/web.php

Route::group(['prefix' => LaravelLocalization::setLocale()], function()
{
	/** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
	Route::get('/', function()
	{
		return View::make('hello');
	});

	Route::get('test',function(){
		return View::make('test');
	});
});

/** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/

Once this route group is added to the routes file, a user can access all locales added into supportedLocales (en and es by default). For example, the above route file creates the following addresses:

// Set application language to English
http://url-to-laravel/en
http://url-to-laravel/en/test

// Set application language to Spanish
http://url-to-laravel/es
http://url-to-laravel/es/test

// Set application language to English or Spanish (depending on browsers default locales)
// if nothing found set to default locale
http://url-to-laravel
http://url-to-laravel/test

The package sets your application locale App::getLocale() according to your url. The locale may then be used for Laravel's localization features.

You may add middleware to your group like this:

Route::group(
[
	'prefix' => LaravelLocalization::setLocale(),
	'middleware' => [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath' ]
], function(){ //...
});

Recommendations

1.: It is strongly recommended to use a redirecting middleware. Urls without locale should only be used to determine browser/default locale and to redirect to the localized url. Otherwise, when search engine robots crawl for example http://url-to-laravel/test they may get different language content for each visit. Also having multiple urls for the same content creates a SEO duplicate-content issue.

2.: It is strongly recommended to localize your links, even if you use a redirect middleware. Otherwise, you will cause at least one redirect each time a user clicks on a link. Also, any action url from a post form must be localized, to prevent that it gets redirected to a get request.

Redirect Middleware

The following redirection middleware depends on the settings of hideDefaultLocaleInURL and useAcceptLanguageHeader in config/laravellocalization.php:

LocaleSessionRedirect

Whenever a locale is present in the url, it will be stored in the session by this middleware.

In there is no locale present in the url, then this middleware will check the following

  • If no locale is saved in session and useAcceptLanguageHeader is set to true, compute locale from browser and redirect to url with locale.
  • If a locale is saved in session redirect to url with locale, unless its the default locale and hideDefaultLocaleInURL is set to true.

For example, if a user navigates to http://url-to-laravel/test and en is the current locale, it would redirect him automatically to http://url-to-laravel/en/test.

LocaleCookieRedirect

Similar to LocaleSessionRedirect, but it stores value in a cookie instead of a session.

Whenever a locale is present in the url, it will be stored in the cookie by this middleware.

In there is no locale present in the url, then this middleware will check the following

  • If no locale is saved in cookie and useAcceptLanguageHeader is set to true, compute locale from browser and redirect to url with locale.
  • If a locale is saved in cookie redirect to url with locale, unless its the default locale and hideDefaultLocaleInURL is set to true.

For example, if a user navigates to http://url-to-laravel/test and de is the current locale, it would redirect him automatically to http://url-to-laravel/de/test.

LaravelLocalizationRedirectFilter

When the default locale is present in the url and hideDefaultLocaleInURL is set to true, then the middleware redirects to the url without locale.

For example, if es is the default locale, then http://url-to-laravel/es/test would be redirected to http://url-to-laravel/test and theApp::getLocale() would be set to es.

Helpers

This package comes with a bunch of helpers.

Localized URLs

Localized URLS taken into account route model binding when generating the localized route, aswell as the hideDefaultLocaleInURL and Translated Routes settings.

Get localized URL

    // If current locale is Spanish, it returns `/es/test`
    <a href="{{ LaravelLocalization::localizeUrl('(/test)') }}">@lang('Follow this link')</a>

Get localized URL for an specific locale

Get current URL in specific locale:

// Returns current url with English locale.
{{ LaravelLocalization::getLocalizedURL('en') }}

Get Clean routes

Returns a URL clean of any localization.

// Returns /about
{{ LaravelLocalization::getNonLocalizedURL('/es/about') }}

Get URL for an specific translation key

Returns a route, localized to the desired locale. If the translation key does not exist in the locale given, this function will return false.

// Returns /es/acerca
{{ LaravelLocalization::getURLFromRouteNameTranslated('es', 'routes.about') }}

Get Supported Locales

Return all supported locales and their properties as an array.

{{ LaravelLocalization::getSupportedLocales() }}

Get Supported Locales Custom Order

Return all supported locales but in the order specified in the configuration file. You can use this function to print locales in the language selector.

{{ LaravelLocalization::getLocalesOrder() }}

Get Supported Locales Keys

Return an array with all the keys for the supported locales.

{{ LaravelLocalization::getSupportedLanguagesKeys() }}

Get Current Locale

Return the key of the current locale.

{{ LaravelLocalization::getCurrentLocale() }}

Get Current Locale Name

Return current locale's name as string (English/Spanish/Arabic/ ..etc).

{{ LaravelLocalization::getCurrentLocaleName() }}

Get Current Locale Direction

Return current locale's direction as string (ltr/rtl).

{{ LaravelLocalization::getCurrentLocaleDirection() }}

Get Current Locale Script

Return the ISO 15924 code for the current locale script as a string; "Latn", "Cyrl", "Arab", etc.

{{ LaravelLocalization::getCurrentLocaleScript() }}

Set view-base-path to current locale

Register the middleware LaravelLocalizationViewPath to set current locale as view-base-path.

Now you can wrap your views in language-based folders like the translation files.

resources/views/en/, resources/views/fr, ...

Map your own custom lang url segments

As you can modify the supportedLocales even by renaming their keys, it is possible to use the string uk instead of en-GB to provide custom lang url segments. Of course, you need to prevent any collisions with already existing keys and should stick to the convention as long as possible. But if you are using such a custom key, you have to store your mapping to the localesMapping array. This localesMapping is needed to enable the LanguageNegotiator to correctly assign the desired locales based on HTTP Accept Language Header. Here is a quick example how to map HTTP Accept Language Header 'en-GB' to url segment 'uk':

// config/laravellocalization.php

'localesMapping' => [
	'en-GB' => 'uk'
],

After that http://url-to-laravel/en-GB/a/b/c becomes http://url-to-laravel/uk/a/b/c.

LaravelLocalization::getLocalizedURL('en-GB', 'a/b/c'); // http://url-to-laravel/uk/a/b/c
LaravelLocalization::getLocalizedURL('uk', 'a/b/c'); // http://url-to-laravel/uk/a/b/c

Creating a language selector

If you're supporting multiple locales in your project you will probably want to provide the users with a way to change language. Below is a simple example of blade template code you can use to create your own language selector.

<ul>
    @foreach(LaravelLocalization::getSupportedLocales() as $localeCode => $properties)
        <li>
            <a rel="alternate" hreflang="{{ $localeCode }}" href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) }}">
                {{ $properties['native'] }}
            </a>
        </li>
    @endforeach
</ul>

Here default language will be forced in getLocalizedURL() to be present in the URL even hideDefaultLocaleInURL = true.

Note that Route Model Binding is supported.

Translated Routes

You may translate your routes. For example, http://url/en/about and http://url/es/acerca (acerca is about in spanish) or http://url/en/article/important-article and http://url/es/articulo/important-article (article is articulo in spanish) would be redirected to the same controller/view as follows:

It is necessary that at least the localize middleware in loaded in your Route::group middleware (See installation instruction).

For each language, add a routes.php into resources/lang/**/routes.php folder. The file contains an array with all translatable routes. For example, like this:

<?php
// resources/lang/en/routes.php
return [
    "about"    =>  "about",
    "article"  =>  "article/{article}",
];
<?php
// resources/lang/es/routes.php
return [
    "about"    =>  "acerca",
    "article"  =>  "articulo/{article}",
];

You may add the routes in routes/web.php like this:

Route::group(['prefix' => LaravelLocalization::setLocale(),
              'middleware' => [ 'localize' ]], function () {

    Route::get(LaravelLocalization::transRoute('routes.about'), function () {
        return view('about');
    });

    Route::get(LaravelLocalization::transRoute('routes.article'), function (\App\Article $article) {
        return $article;
    });

    //,...
});

Once files are saved, you can access http://url/en/about , http://url/es/acerca , http://url/en/article/important-article and http://url/es/articulo/important-article without any problem.

Translatable route parameters

Maybe you noticed in the previous example the English slug in the Spanish url:

http://url/es/articulo/important-article

It is possible to have translated slugs, for example like this:

http://url/en/article/important-change
http://url/es/articulo/cambio-importante

However, in order to do this, each article must have many slugs (one for each locale). Its up to you how you want to implement this relation. The only requirement for translatable route parameters is, that the relevant model implements the interface LocalizedUrlRoutable.

Implementing LocalizedUrlRoutable

To implement \Mcamara\LaravelLocalization\Interfaces\LocalizedUrlRoutable, one has to create the function getLocalizedRouteKey($locale), which must return for a given locale the translated slug. In the above example, inside the model article, getLocalizedRouteKey('en') should return important-change and getLocalizedRouteKey('es') should return cambio-importante.

Route Model Binding

To use route-model-binding, one should overwrite the function resolveRouteBinding($slug) in the model. The function should return the model that belongs to the translated slug $slug. For example:

public function resolveRouteBinding($slug)
{
        return static::findByLocalizedSlug($slug)->first() ?? abort(404);
}

Tutorial Video

You may want to checkout this video which demonstrates how one may set up translatable route parameters.

Events

You can capture the URL parameters during translation if you wish to translate them too. To do so, just create an event listener for the routes.translation event like so:

Event::listen('routes.translation', function($locale, $attributes)
{
	// Do your magic

	return $attributes;
});

Be sure to pass the locale and the attributes as parameters to the closure. You may also use Event Subscribers, see: http://laravel.com/docs/events#event-subscribers

Caching routes

To cache your routes, use:

php artisan route:trans:cache

... instead of the normal route:cache command. Using artisan route:cache will not work correctly!

For the route caching solution to work, it is required to make a minor adjustment to your application route provision.

In your App's RouteServiceProvider, use the LoadsTranslatedCachedRoutes trait:

<?php
class RouteServiceProvider extends ServiceProvider
{
    use \Mcamara\LaravelLocalization\Traits\LoadsTranslatedCachedRoutes;

For more details see here.

Common Issues

POST is not working

This may happen if you do not localize your action route that is inside your Routes::group. This may cause a redirect, which then changes the post request into a get request. To prevent that, simply use the localize helper.

For example, if you use Auth::routes() and put them into your Route::group Then

<form action="/logout" method="POST">
<button>Logout</button>
</form>

will not work. Instead, one has to use

<form action="{{  \LaravelLocalization::localizeURL('/logout') }} " method="POST">
<button>Logout</button>
</form>

MethodNotAllowedHttpException

If you do not localize your post url and use a redirect middleware, then the post request gets redirected as a get request. If you have not defined such a get route, you will cause this exception.

To localize your post url see the example in POST is not working.

Validation message is only in default locale

This also happens if you did not localize your post url. If you don't localize your post url, the default locale is set while validating, and when returning to back() it shows the validation message in default locale.

To localize your post url see the example in POST is not working.

Testing

During the test setup, the called route is not yet known. This means no language can be set. When a request is made during a test, this results in a 404 - without the prefix set the localized route does not seem to exist.

To fix this, you can use this function to manually set the language prefix:

// TestCase.php
protected function refreshApplicationWithLocale($locale)
{
    self::tearDown();
    putenv(LaravelLocalization::ENV_ROUTE_KEY . '=' . $locale);
    self::setUp();
}

protected function tearDown()
{
    putenv(LaravelLocalization::ENV_ROUTE_KEY);
    parent::tearDown();
}

// YourTest.php
public function testBasicTest()
{
    $this->refreshApplicationWithLocale('en');
    // Testing code
}

Collaborators

Ask mcamara if you want to be one of them!

Changelog

View changelog here -> changelog

License

Laravel Localization is an open-sourced laravel package licensed under the MIT license

Comments
  • Save last language selected?

    Save last language selected?

    I'm trying to save the last language selected with the Cookie option.

    if my page is "page.com" and my last visit is to "page.com/es/perfil", I want redirect to profile (spanish) if I go to page.com again, but this doesn't seem to work. It is always getting the default language (english in this case) so it's redirecting to page.com/en/profile.

    opened by Luddinus 42
  • Language bar links issues

    Language bar links issues

    I'm having troubles with the language bar

    I am in this URL: http://localhost/mysite/public/

    It generates correctly the language links, but if I enter spanish version's site http://localhost/mysite/public/es, it generates these links (english, german and spanish)

    array (size=3) 'en' => string 'http://localhost/mysite/public/en/es' (length=32) 'es' => string 'http://localhost/mysite/public/es/es' (length=32) 'de' => string 'http://localhost/mysite/public/de/es' (length=32)

    What am I doing wrong?

    opened by Ulrira 29
  • getLocalizedURL doesn't translate routes

    getLocalizedURL doesn't translate routes

    Hello.

    Laravel-localization works well on my application. When I am on the homepage if I switch language and navigate on the application, all is running well, routes are translated as expected in all links, menus etc.

    The problem is when I am on a page, if I click on the switch languages this is what I have :

    - http://app.dev/fr/titres/mon-titre
    - http://app.dev/en/titres/mon-titre
    - http://app.dev/es/titres/mon-titre
    

    This is what I should have :

    - http://app.dev/fr/titres/mon-titre
    - http://app.dev/en/titles/mon-titre
    - http://app.dev/es/titulos/mon-titre
    

    On my header.blade.php, this is what I have :

    
    @foreach(Localization::getSupportedLocales() as $lang => $properties)
        <a
            href="{{Localization::getLocalizedURL($lang)}}"
            @if(Localization::getCurrentLocale() == $lang) class="active" @endif
        >
            {{$lang}}
        </a>
    @endforeach
    
    

    Insofar as all is working as expected for the language when we are on a good URL ... what is the issue with that problem ? I saw many posts about similar problems with the getLocalizedURL() method, I tried many "issues" without success ... :/

    opened by francoisdusautoir 27
  • Unit testing localized routes

    Unit testing localized routes

    Hello,

    I'm trying to unit test calling to localized routes with a very simple test, but it is not working. I guess it is because the routes are loaded with the default prefix just one time on the testing flow.

    On a browser, when the routes.php is excecuted for every request, everything works fine.

    Is this an expected behaviour? Am i doing something wrong? Am i supposed to test this?

    Here is the code of the test:

    class ExampleTest extends TestCase {
    
        /**
         * A basic functional test example.
         *
         * @return void
         */
        public function testBasicExample()
        {
            $crawler = $this->client->request('GET', '/');
    
            $this->assertTrue($this->client->getResponse()->isOk());
        }
    
        /**
         * A basic functional test example with language.
         *
         * @return void
         */
        public function testBasicExampleWithLanguage()
        {
            $crawler = $this->client->request('GET', '/es');
    
            $this->assertTrue($this->client->getResponse()->isOk());
        }
    
    }
    

    And here is the error i'm getting when excecuting phpunit:

    image

    My routes.php is:

    Route::group(array('prefix' => LaravelLocalization::setLocale(), 
                       'before' => 'LaravelLocalizationRedirectFilter'), function()
    {
        Route::get('/', function() {
            return 'home';
        });
    
        Route::get('test',function(){
            return 'test';
        });
    });
    
    opened by leonardoalifraco 27
  • LaravelLocalization::getLocalizedURL issues!

    LaravelLocalization::getLocalizedURL issues!

    Hello, I am having some issues with this function which i am not sure if it is a bug or i am missing something. Probably there is something i am missing.

    I am trying to use this function to build localized urls for my app like so:

    <a href="{{ LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLanguage(), $category->category_slug) }}">whatever</a>
    

    The above example doen't work when in my '/' route. However a similar implementation works perfectly in other routes.

    What is more i cannot generate localized urls for my '/' route while trying the following.

    LaravelLocalization::getLocalizedURL(LaravelLocalization::getCurrentLanguage(), '/')
    
    opened by nikosv 26
  • Arabic Routes are being stuck

    Arabic Routes are being stuck

    I've app with 5 different languages, only in Arabic routes the app is being stuck using this route chaning to different language will change the language code only:

    i.e:

    xxx.com/en/hotels

    works just fine, chaning it into: xxx.com/ar/فنادق

    works fine but:

    when I try to change language into Netherlands : xxx.com/nl/فنادق

    When I changed the value of hotels key inside resources/lang/ar/routes.php into latin characters the problem went away!!

    I have no idea why, perhabs you could help me because I've a lot of slugs in Arabic.

    my routes.php hotels section:

    Route::group(
        array( 'prefix' => LaravelLocalization::setLocale(),
            'middleware' => [ 'localizationRedirect' ]),
             function() {
               Route::resource(LaravelLocalization::transRoute('routes.hotels'),
                                'HotelsController' , array('as'=>'hotelsPath'));
    });
    
    opened by mkwsra 23
  • Does not keep the changed language

    Does not keep the changed language

    I have installed new Laravel application (5.22) and added laravel-localization package. When I try to change the app language it changes it, however the application does not keep it set. After another request it is changed back to the language which was set before. Could it be connected with some kind of Symfony or Laravel update? It is used to work in a proper way a few days ago.

    Update - when I run Session::get('locale') it returns null. It looks like the session does not change at all.

    Thank you

    opened by matusmacko 19
  • When you change hideDefaultLocaleInURL to true, access to the default language will appear 404

    When you change hideDefaultLocaleInURL to true, access to the default language will appear 404

    Hello, first of all thank you very much for your plugin, he is very good I am having a problem now,When I change hideDefaultLocaleInURL to true, access to the default language will appear 404. www.test.com/contact Can be accessed www.test.com/es/contact A 404 error has occurred and there is no redirect I have already registered and added middleware Waiting for your reply, thank you again for your plugin

    bug 
    opened by monkey-qiang1994 18
  • Update LaravelLocalizationServiceProvider.php

    Update LaravelLocalizationServiceProvider.php

    Rename config file in the LaravelLocalizationServiceProvider. This way we keep all our files named the same way.

    I expect that if this get's merged it won't be in the current version.

    opened by wotta 18
  • Language selector not working if hideDefaultLocaleInURL = TRUE

    Language selector not working if hideDefaultLocaleInURL = TRUE

    Hello, Language selector not working when the option hideDefaultLocaleInURL is true. It is automatically redirected to the language selected previously. Example: ES: http://local.com/es/acerca (its work ) DE: http://local.com/de/uber (its work ) EN: http://local.com/about ( Redirect to http://local.com/es/acerca ) , It only works if I go to this url: http://local.com/en/about (duplicate content for SEO)

    Using: Laravel 5

    :(

    Is there any solution? thanks.

    opened by neysi 17
  • Help on installing

    Help on installing

    Hi. I tried to instal on my localhost using composer but have some errors. First i Add Laravel Localization to my composer.json file : "mcamara/laravel-localization": "dev-master" then i run composer install After i edit app/config/app.php provider and alias key and then i run php artisan config:publish mcamara/laravel-localization I get an error i will attach the file. What i am doing wrong? screen

    opened by closca 17
  • see routes in all language files

    see routes in all language files

     $route = collect(app('router')->getRoutes())->first(function($route) use($url){
                return $route->matches(request()->create($url));
     });
    

    I'm trying to catch the current rotation at the current address with this code, but only the rotations in lang/fr/routes.php are listed. The rotations in lang/en/routes.php are not listed, so when switching from en to fr, I can't catch the current url.

    opened by mertbuldur 0
  • Tests returning 404

    Tests returning 404

    We have followed the steps outlined in the README to set up testing but we are still getting a 404 error when running the default laravel tests.

    <?php
    
    namespace Tests;
    
    use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
    use Mcamara\LaravelLocalization\LaravelLocalization;
    
    abstract class TestCase extends BaseTestCase
    {
        use CreatesApplication;
    
        protected function refreshApplicationWithLocale($locale): void
        {
            self::tearDown();
            putenv(LaravelLocalization::ENV_ROUTE_KEY . '=' . $locale);
            self::setUp();
        }
    
        protected function tearDown(): void
        {
            putenv(LaravelLocalization::ENV_ROUTE_KEY);
            parent::tearDown();
        }
    }
    
    namespace Tests\Feature;
    
    // use Illuminate\Foundation\Testing\RefreshDatabase;
    use Tests\TestCase;
    
    class ExampleTest extends TestCase
    {
        /**
         * A basic test example.
         *
         * @return void
         */
        public function test_the_application_returns_a_successful_response()
        {
            $this->refreshApplicationWithLocale('en-GB');
    
            $response = $this->get('/');
    
            $response->assertStatus(200);
        }
    }
    
      Tests\Feature\ExampleTest > the application returns a successful response
      Expected response status code [200] but received 404.
      Failed asserting that 200 is identical to 404.
    
    • Version of Laravel: 9.19
    • Version of the Laravel-localization package: 1.7
    • Which middleware is used in Route::groups: [ 'localeSessionRedirect', 'localizationRedirect', 'localeViewPath']
    opened by triciacuninghame 1
  • How to use this package to automatically redirect my site to the Web Browser's default language if my language URL is of type

    How to use this package to automatically redirect my site to the Web Browser's default language if my language URL is of type "get" whose language setting name is "lang"

    Hello.

    I don't see anywhere in the README File how to use this package to automatically redirect my site to the Web Browser's default language if my language URL is of type get whose language setting name is lang like this:

    French: https://ourwebsite.com/login?lang=fr English: https://ourwebsite.com/login?lang=en Spanish: https://ourwebsite.com/login?lang=es German: https://ourwebsite.com/login?lang=de

    ???

    Please answer us through sample code as it is clearer with sample code. Waiting for a favorable reply.

    opened by chegmarco1989 0
  • default language initialized before tenant

    default language initialized before tenant

    I have install stancl/tenancy to create multi store tenant . and i have mcamara to setup store default language from settings database table .

      `if (Schema::hasTable('languages') && Schema::hasTable('settings')):
           $default_language       = settingHelper('default_language');
        if (!empty($default_language)) :
            Config::set('app.locale', $default_language);
        endif;
        //supported language setting to laravellocalization
        $languageList              =  Language::where('status',1)->get();
        $supportedLocales          = array();
    
        if ($languageList->count() > 0) :
            foreach ($languageList as $lang) :
                $langConfigs            = $lang->languageConfig->select('name', 'script', 'native', 'regional')->get();
                foreach ($langConfigs as $langConfig) :
                    $langConfig->flag_icon = $lang->flag;
                    $supportedLocales[$lang->locale] = $langConfig;
                endforeach;
            endforeach;
          //  LaravelLocalization::setSupportedLocales($supportedLocales);
            Config::set('laravellocalization.supportedLocales', $supportedLocales);
    
        endif;
       endif;`
    

    but my problem is : The default language does not change, it always remains English because the language settings are configured before tenant

    opened by gogo207 0
  • Redirect to main lang now work with hideDefaultLocaleInURL = true

    Redirect to main lang now work with hideDefaultLocaleInURL = true

    I have a code in a blade

    @php
        $j = 0;
        @endphp
        @foreach(LaravelLocalization::getLocalesOrder() as $localeCode => $properties)
            @php
                $j ++;
            @endphp
            @if($j === 1)
                <a hreflang="{{ $localeCode }}" href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], false) . '/' }}">
                    {{ $properties['native'] }}
                </a>&nbsp;
            @else
                <a rel="alternate" hreflang="{{ $localeCode }}" href="{{ LaravelLocalization::getLocalizedURL($localeCode, null, [], true) . '/' }}">
                    {{ $properties['native'] }}
                </a>&nbsp;
            @endif
        @endforeach
    

    And code in routes/web.php

    /** ADD ALL LOCALIZED ROUTES INSIDE THIS GROUP **/
    Route::group(
        [
            'prefix' => LaravelLocalization::setLocale(),
            'middleware' => ['localeSessionRedirect', 'localizationRedirect', 'localeViewPath']
        ], function () {
    
        Route::get('/', function () {
            return view('index');
        });
    
        /* Blog */
        Route::get('/blog/', [BlogController::class, 'index'])->name('blog.index');
        /* END Blog */
    });
    /** OTHER PAGES THAT SHOULD NOT BE LOCALIZED **/
    
    1. I open the page http://127.0.0.1/blog
    2. Click to another lang (for example EN) and go to http://127.0.0.1/en/blog
    3. I click to the first lang (without prefix) and the page redirected to http://127.0.0.1/en/blog, but should to http://127.0.0.1/blog with default lang.
    opened by igramnet 0
Releases(v1.7.0)
Owner
Marc Cámara
Marc Cámara
A self-hosting localization tool

Localiser A self-hosting localization tool. Requirements PHP ^7.3 Usage Fetch cached locales GET

Memo Chou 6 Mar 10, 2022
Provides support for message translation and localization for dates and numbers.

The I18n library provides a I18n service locator that can be used for setting the current locale, building translation bundles and translating messages. Additionally, it provides the Time and Number classes which can be used to output dates, currencies and any numbers in the right format for the specified locale.

CakePHP 26 Oct 22, 2022
Brings localization feature to tightenco/jigsaw using JSON files

Jigsaw localization Brings localization feature to tightenco/jigsaw using JSON files. Get started Setup Bring jigsaw-localization to your Jigsaw proje

Elaborate Code 6 Nov 1, 2022
Easy multilingual urls and redirection support for the Laravel framework

Linguist - Multilingual urls and redirects for Laravel This package provides an easy multilingual urls and redirection support for the Laravel framewo

Tanel Tammik 189 Jul 18, 2022
List of 77 languages for Laravel Framework 4, 5, 6, 7 and 8, Laravel Jetstream , Laravel Fortify, Laravel Cashier and Laravel Nova.

Laravel Lang In this repository, you can find the lang files for the Laravel Framework 4/5/6/7/8, Laravel Jetstream , Laravel Fortify, Laravel Cashier

Laravel Lang 6.9k Dec 29, 2022
75 languages support for Laravel 5 application based on Laravel-Lang/lang.

Laravel-lang 75 languages support for Laravel 5 application based on Laravel-Lang/lang. Features Laravel 5+ && Lumen support. Translations Publisher.

安正超 1.3k Jan 4, 2023
[Deprecated] A Laravel package for multilingual models

This package has been deprecated. But worry not. You can use Astrotomic/laravel-translatable. Laravel-Translatable If you want to store translations o

Dimitris Savvopoulos 2k Dec 25, 2022
Better translation management for Laravel

Better localization management for Laravel Introduction Keeping a project's translations properly updated is cumbersome. Usually translators do not ha

Waavi 354 Dec 18, 2022
Package to manage Laravel translations locally

Translation Manager For Laravel Easy to use package that helps you with the translation of your Laravel application locally. Features ✅ Check all loca

null 5 Jan 8, 2022
Support multiple language resources for Laravel

Laratrans Support multiple language resources for Laravel. Docs Installation composer require lechihuy/laratrans After you install the package success

Lê Chí Huy 3 Dec 21, 2021
Laravel translation made __('simple').

Translation.io client for Laravel 5.5+/6/7/8 Add this package to localize your Laravel application. Use the official Laravel syntax (with PHP or JSON

Translation.io 109 Dec 29, 2022
Manage Laravel translation files

Laravel 5 Translation Manager For Laravel 4, please use the 0.1 branch! This is a package to manage Laravel translation files. It does not replace the

Barry vd. Heuvel 1.5k Jan 4, 2023
A GUI for managing JSON translation files in your laravel projects.

Laravel Language Manager Langman is a GUI for managing your JSON language files in a Laravel project. Installation Begin by installing the package thr

Mohamed Said 515 Nov 30, 2022
A Gui To Manage Laravel Translation Files

Lingo A file based translation manager, which unlike other Lang managers don't need a database connection to handle the translation. Installation comp

Muah 97 Dec 5, 2022
Generates a vue-i18n compatible include file from your Laravel translations

This is fork of martinlindhe/laravel-vue-i18n-generator to give Laravel 8+ support for this excellent package.

Alefe Souza 1 Nov 11, 2021
Easy localization for Laravel

Laravel Localization Easy i18n localization for Laravel, an useful tool to combine with Laravel localization classes. The package offers the following

Marc Cámara 3k Jan 4, 2023
Easy Localization for Laravel

Query String Localization Package for Laravel Use this package to localize your laravel application via query strings easily. Features: Localization b

Cosnavel 50 Dec 15, 2021
A Laravel Larex plugin to import/export localization strings from/to Crowdin

Laravel Larex: Crowdin Plugin A Laravel Larex plugin to import/export localization strings from/to Crowdin ?? Requirements PHP 7.4 | 8.0 Laravel ≥ 7 L

Luca Patera 4 Oct 27, 2021
Laravel URL Localization Manager - [ccTLD, sub-domain, sub-directory].

Laravel URL Localization - (ccTLD, sub-domain, sub-directory). with Simple & Easy Helpers. Afrikaans Akan shqip አማርኛ العربية հայերեն অসমীয়া azərbayca

Pharaonic 2 Aug 7, 2022
🎌 Laravel Localization Helper :: Easily add translation variables from Blade templates.

LocalizationHelper Package for convenient work with Laravel's localization features and fast language files generation. Take a look at contributing.md

Awes.io 36 Jul 18, 2022