Skip to content

Instantly share code, notes, and snippets.

@Saifallak
Last active August 30, 2022 05:01
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Saifallak/f87019874c579bbdec1076b641c81568 to your computer and use it in GitHub Desktop.
Save Saifallak/f87019874c579bbdec1076b641c81568 to your computer and use it in GitHub Desktop.
Laravel Localization Middlewares.

Getting started

How to Localize Laravel ?

Laravel Localization Lang Files.

    "require-dev": {
        ...
        "laravel-lang/lang": "^11.0",
        "laravel-lang/publisher": "^14.1"
    },
  • Optional in update scripts (post-update-cmd) in composer.json add update languages cmd to keep them updated
    "scripts": {
        "post-update-cmd": [
            ...
            "@php artisan lang:update"
        ],
      }
  • now run php artisan lang:add {LANGUAGES} to add the lang files you need ex: php artisan lang:add ar en fr

and now, we got all lang files we need in lang\* folder for L9 or resources\lang\* for L<9.

How to localize Our Website/API? we need middleware.

  • in app\Http\Middlwares Create 3 files ( attached below )
  • in app/Http/Kernel.php add:
    • in $middlewareGroups, web section \App\Http\Middleware\WebLocalization::class
    • in $middlewareGroups, api section \App\Http\Middleware\ApiLocalization::class
    /**
     * The application's route middleware groups.
     *
     * @var array<string, array<int, class-string|string>>
     */
    protected $middlewareGroups = [
        'web' => [
            //...
            \App\Http\Middleware\WebLocalization::class,
        ],

        'api' => [
            //...
            \App\Http\Middleware\ApiLocalization::class,
        ],
    ];

Last step to tell our project which languages we support.

  • in config/app.php to support ar,en add and so on:
'available_locales' => [
        'en' => [
            'dir' => 'ltr',
            'name' => 'English',
            'native' => 'English',
            'script' => 'Latn',
            'flag_code' => 'us',
        ],
        'ar' => [
            'dir' => 'rtl',
            'name' => 'Arabic',
            'native' => 'العربية',
            'script' => 'Arab',
            'flag_code' => 'sa',
        ],
    ],

now our project is localized and knows which language to use when getting request from web and api.

  • for api they must send you Accept-Language header with language ex: ar
  • for web you can change the language just by passing ?lang=ar at the end of url

lastly our layout blade file should contain at the start of it

<!DOCTYPE html>
@php
    $lang = app()->getLocale();
    $dir = config('app.available_locales')[app()->getLocale()]['dir'] ?? 'ltr';
@endphp

<html lang="{{ $lang }}" dir="{{ $dir }}">
<!-- ... -->
</html>

Made with ♥ By

<?php
namespace App\Http\Middleware;
/**
* This File was made by [AQuadic Software Solutions](AQuadic.com).
* if you are happy with this file and used it,
* send us thanks letter on [hello@aquadic.com](mailto:hello@aquadic.com)
*
* File Path: app/Http/Middleware/ApiLocalization.php
*/
class ApiLocalization extends LocalizationMiddleware
{
}
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* This File was made by [AQuadic Software Solutions](AQuadic.com).
* if you are happy with this file and used it,
* send us thanks letter on [hello@aquadic.com](mailto:hello@aquadic.com)
*
* File Path: app/Http/Middleware/Localization.php
*/
class LocalizationMiddleware
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure(Request): (Response|RedirectResponse) $next
* @return Response|RedirectResponse
*/
public function handle(Request $request, Closure $next): mixed
{
$this->getLocale($request, null);
return $next($request);
}
protected function getLocale(Request $request, ?string $defaultLocale): string
{
if (! $defaultLocale) {
$defaultLocale = $this->parseHttpLocale($request) ?? config('app.locale');
}
if (! in_array($defaultLocale, array_keys(config('app.available_locales')))) {
$defaultLocale = array_keys(config('app.available_locales'))[0];
}
app()->setLocale($defaultLocale);
return $defaultLocale;
}
private function parseHttpLocale(Request $request): string
{
$list = explode(',', $request->header('Accept-Language', config('app.locale')));
$locales = collect($list)
->map(function ($locale) {
$parts = explode(';', $locale);
$mapping['locale'] = trim($parts[0]);
if (isset($parts[1])) {
$factorParts = explode('=', $parts[1]);
$mapping['factor'] = $factorParts[1];
} else {
$mapping['factor'] = 1;
}
return $mapping;
})
->sortByDesc(function ($locale) {
return $locale['factor'];
});
return explode($locales->first()['locale'], '-')[0];
}
}
<?php
namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Response;
/**
* This File was made by [AQuadic Software Solutions](AQuadic.com).
* if you are happy with this file and used it,
* send us thanks letter on [hello@aquadic.com](mailto:hello@aquadic.com)
*
* File Path: app/Http/Middleware/WebLocalization.php
*/
class WebLocalization extends LocalizationMiddleware
{
/**
* Handle an incoming request.
*
* @param Request $request
* @param Closure(Request): (Response|RedirectResponse) $next
* @return Response|RedirectResponse
*/
public function handle(Request $request, Closure $next): mixed
{
$locale = $request->get('lang') ?: $request->session()->get('locale');
$locale = $this->getLocale($request, $locale);
$request->session()->put('locale', $locale);
return $next($request);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment