Implementing Multilingual Support in Laravel Using Laravel Localization and Mcamara Package

Implementing Multilingual Support in Laravel Using Laravel Localization and Mcamara Package

Creating a multilingual Laravel application is essential for reaching a global audience. Laravel provides a built-in localization system, and the Mcamara Laravel Localization package enhances it by adding advanced features such as URL-based language switching. This guide covers both approaches for implementing multilingual support in Laravel.


1. Built-in Laravel Localization

Laravel comes with native support for localization, allowing you to store translations in language files within the resources/lang directory.

Setting Up Localization

  1. Create language directories inside resources/lang:

    resources/lang/en
    resources/lang/es
    
  2. Add a language file:

    // resources/lang/en/messages.php
    return [
        'welcome' => 'Welcome!',
        'goodbye' => 'Goodbye!',
    ];
    
    // resources/lang/es/messages.php
    return [
        'welcome' => '¡Bienvenido!',
        'goodbye' => '¡Adiós!',
    ];
    
  3. Using translations in views:

    <p>{{ __('messages.welcome') }}</p>
    
  4. Changing the default locale in config/app.php:

    'locale' => 'en',
    
  5. Setting locale dynamically:

    App::setLocale('es');
    

2. Using Mcamara Laravel Localization Package

The Mcamara Laravel Localization package adds advanced features like URL-based language switching.

Installation

composer require mcamara/laravel-localization

Register Service Provider

Add the service provider in config/app.php:

Mcamara\LaravelLocalization\LaravelLocalizationServiceProvider::class,

Publish Configuration

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

Middleware Setup

Add the middleware to app/Http/Kernel.php:

protected $middlewareGroups = [
    'web' => [
        \Mcamara\LaravelLocalization\Middleware\LaravelLocalizationRedirectFilter::class,
        \Mcamara\LaravelLocalization\Middleware\LocaleSessionRedirect::class,
    ],
];

Using Language Switcher

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

Routing with Localization

Route::group(['prefix' => LaravelLocalization::setLocale()], function() {
    Route::get('/', function() {
        return view('welcome');
    });
});

3. Caching Translated Routes

To improve the performance of your multilingual Laravel application, you can cache the translated routes using the following Artisan command:

php artisan route:trans:cache

This caches the localized routes, reducing the processing overhead during each request. Remember to clear the route cache after making changes to your routes:

php artisan route:clear

4. Best Practices for Multilingual Laravel Apps

  • Organize Language Files: Keep translations organized by feature or module.
  • Use Key Naming Conventions: Use meaningful keys for clarity.
  • Optimize Performance: Cache translations in production using php artisan config:cache.
  • Test Language Switching: Ensure all content translates correctly across all languages.

Helpful Resources

Conclusion

Laravel provides a powerful built-in localization system, and the Mcamara Laravel Localization package adds even more flexibility. By following these steps, you can easily create a multilingual Laravel application that enhances user experience and expands your audience globally.

Recent blogs
Структурные паттерны в программировании

Структурные паттерны в программировании

Порождающие паттерны в программировании

Порождающие паттерны в программировании

Генераторы и итераторы в PHP

Генераторы и итераторы в PHP

Объектно-ориентированное программирование в PHP

Объектно-ориентированное программирование в PHP

Структуры данных в PHP

Структуры данных в PHP