How to Set Up Localization in Laravel

How to Set Up Localization in Laravel

Step 1: Configure Laravel Localization

Open the config/app.php file and set the default locale:

'locale' => 'en',

You can also set a fallback locale:

'fallback_locale' => 'en',

Step 2: Create Language Files

Laravel stores language files in the resources/lang/ directory. Create a new folder for the desired language (e.g., es for Spanish) and add translation files:

resources/lang/es/messages.php

Example content of messages.php:

 'Bienvenido a nuestra aplicación',
];

Step 3: Use Translations in Views

Use the __() helper function or @lang directive in Blade templates:

{{ __('messages.welcome') }}
@lang('messages.welcome')

Step 4: Change Locale Dynamically

To change the language dynamically, use the following code in a controller:

App::setLocale('es');

Step 5: Set Locale from Middleware

Create middleware to set the locale based on user preference or session:

php artisan make:middleware LocaleMiddleware

Modify the middleware file:

public function handle($request, Closure $next)
{
    if (session()->has('locale')) {
        App::setLocale(session('locale'));
    }
    return $next($request);
}

Conclusion

Now your Laravel application supports multiple languages. Users can switch between different locales dynamically.

0 Comments