Localization

Laravel Localization

Laravel Local Cheet Sheet

Method Description
app()->getLocale() Get current locale
app()->setLocale('zh_TW'); Set locale
app()->isLocale('zh_TW'); Check the locale

Set Default Localization Language

You may configure a "fallback language", which will be used when the active language DOES NOT contain a given translation string.

// config/app.php
return [
    // Default language
    'locale' => 'zh_TW',
    // Fallback language
    'fallback_locale' => 'en',
];

Localization Language Directory

PHP Array Format

/lang
    /en
        messages.php
    /es
        messages.php
    /zh_TW
        messages.php

JSON Format

/lang
    en.json
    es.json
    zh_TW.json

Configuring The Locale

use Illuminate\Support\Facades\App;
 
Route::get('/greeting/{locale}', function ($locale) {
    if (! in_array($locale, ['en', 'es', 'zh_TW'])) {
        abort(400);
    }
 
    App::setLocale($locale);
 
    //
    app()->setLocale($locale);
});

Replacing Parameters In Translation Strings

echo __('messages.welcome', ['name' => 'dayle']);
echo __('messages.goodbye', ['name' => 'dayle']);
// lang/en/messages.php
return [
    'welcome' => 'Welcome, :NAME', // Welcome, DAYLE
    'goodbye' => 'Goodbye, :Name', // Goodbye, Dayle
]

Localization Accept Language Middleware

  1. if cookie exist the locale setting then use the cookie locale
  2. Get the preferred language from header (accept-language)
<?php

namespace App\Middleware;

use Closure;

class AcceptLanguageMiddleware
{
    public function handle($request, Closure $next)
    {
        // cookie locale
        $locale_cookie_name = env('LOCALE_COOKIE_NAME', 'locale');
        $locale_cookie = $request->cookie($locale_cookie_name);
        if ($locale_cookie) {
            // Cookie locale exist
            app()->setLocale($locale_cookie);
            return $next($request);
        }

        // Accept language header
        $preferred_language = request()->getPreferredLanguage();
        if ($preferred_language) {
            app()->setLocale($preferred_language);
            return $next($request);
        }

        // default language
        return $next($request);
    }
}

Reference