Localization in Laravel

Localization in Laravel

Step 1: Configure Localization Settings

Open the config/app.php file and set the locale to your default language. For example, if you want to use English (en), find the 'locale' setting and set it to 'en'.

'locale' => 'en',        


Step 2: Create Language Files

Create language files for the languages you want to support. Laravel uses a directory-based structure for language files. Inside the resources/lang directory, create subdirectories for each language code (e.g., en for English, fr for French).

Create a file resources/lang/en/messages.php with the following content:

// resources/lang/en/messages.php
return [
    'welcome' => 'Welcome to our application!',
    'date' => 'Date: :date',
    'apples' => '{0} No apples|{1} One apple|[2,*] :count apples',
];        

Create a similar file for French: resources/lang/fr/messages.php


Step 3: Use Localization in Views

In your Blade views, use the trans helper function or the @lang directive to display translated strings:

<!-- Using trans helper function -->
{{ trans('messages.welcome') }}

<!-- Using @lang directive -->
@lang('messages.welcome')        


Step 4: Dynamic Content Localization

For dynamic content like date formats, use the __ function with placeholders:

{{ __('messages.date', ['date' => now()->formatLocalized('%A %d %B %Y')]) }}        


Step 5: Pluralization

Handle pluralization using the trans_choice function in your language files:

// In resources/lang/en/messages.php
'apples' => '{0} No apples|{1} One apple|[2,*] :count apples',        

And in your Blade views:

{{ trans_choice('messages.apples', $count) }}        


Step 6: Retreiving Locales From Request

To retreive the application locale, you can use the given middleware:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SetLocaleLanguage
{
	public function handle(Request $request, Closure $next)
	{
		$lang = session('lang', 'en');
		app()->setLocale($lang);

		return $next($request);
	}
}        


Step 7: Switching Locales Dynamically

To change the application locale dynamically, you can use this SetLocaleLanguage method:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

class SetLocaleLanguage
{
	public function handle(Request $request, Closure $next)
	{
		$lang = session('lang', 'en');
		app()->setLocale($lang);

		return $next($request);
	}
}        


Step 8: Route should be something like this:

Route::get('/change-locale/{locale}', [LanguageController::class, 'locale'])->name('locale.change');        


Visit your application in the browser, and add ?lang=fr to the URL to test the French localization.

That's it! You now have a localized Laravel application ready to serve a global audience. Happy coding! ????

要查看或添加评论,请登录

Nugzar Skhireli的更多文章

社区洞察

其他会员也浏览了