Laravel 9 Localization Example Tutorial – 3 Methods

For instance, I am sharing Laravel 9 localization example tutorial, 3 methods to share different methods to use Laravel’s localization. Then, you will learn how to perform Laravel localization and create your application in multiple languages. To illustrate, I used Laravel localization routes, Laravel Middleware, Laravel controller for Laravel localization example.

Laravel 9 Localization Example

Laravel 9 Localization Example

For example, all methods for Laravel 9 localization example are using Laravel’s own localization feature. So, I am writing and assumed that you already know the below.

  • Firstly, You are using Laravel 9 for this Laravel Tutorial.
  • Secondly, You have necessary PHP Programming and Laravel Framework knowledge.
  • Thirdly, you are using localhost as your domain name.
    • If not, then replace localhost with your domain name or IP address (depending on your installation)

Laravel Create Project Composer Command

This is optional, however, if you have not created the Laravel app then you may go ahead and execute the below command to create a Laravel project name example.

composer create-project laravel/laravel example

Multi Language Support in Laravel

Simultaneously, You need to add multi langauge support in Laravel before working on Laravel localization. Therefore, you have to add supportedLocales in config\app.php as under. Ideally, you can add this after locale or fallback_locale section.

'supportedLocales' => ['en','ur'],

1. Routes Method: Laravel 9 Localization

Above all, forget all the hustle bustle about Laravel 9 localization tutorials and use this simplest Laravel Localization Routes method. Of course, you need a language switcher to decide and use the required language.

1.1 Laravel Localization Routes

In addition, You need to create Laravel localization routes before using any method to create Laravel localization.

# routes/web.php
Route::get('/', function () {
    return redirect(\session()->get('appLocale'));
});

Subsequently, You may found that Laravel localization route is not working after adding above Laravel localization route.

1.2 Laravel Localization Routes Not Working

Specifically, You can see the image below that after adding the code above, Laravel localization route is not working.

Laravel Localization Routes Not Working

Indeed, in example above, you can see two highlighted points for Laravel localization not working in routes.

  1. Firstly, Laravel Localization route redirecting to current locale.
  2. Secondly, equally important, You can see that Laravel localization routes are not working because you need to add locale prefix in routes. So, let’s add local in the default route in Laravel.
# routes/web.php
Route::get('/{locale}', function () {
    return view('welcome');
});
Laravel Localization Routes

Of course, You can use language switcher to switch between the configured fallback_locale in Config\App.php file and you do not need any extra effort to manage this. Simply refresh the not found page to see the magic.

Laravel Application Fallback Locale – The fallback locale determines the locale to use when the current one is not available. You may change the value to correspond to any of the language folders that are provided through your application.

Laravel Localization Routes Example

2. Middleware Method: Laravel 9 Localization

Secondly, you can use Laravel Middleware for Laravel 9 localization example. Therefore, you can use Laravel Middleware to pass locale to all Laravel routes aesthetically.

2.1 Create Middleware in Laravel

Accordingly, you need to create Middleware in Laravel 9 before using it. For instance, Laravel Middleware are created in app/Http/Middleware folder. So, let’s use this command to create Middleware in Laravel.

php artisan make:middleware SetLocale

Indeed, above command will create SetLocale middlwware in Laravel 9, in app/Http/Middleware folder.

2.2 Locale Middleware Laravel Code Example

Of course, after creating your setLocale Middlware, you need to add below code before return $next($request) under public function handle(Request $request, Closure $next).

#setLocale Middlware
$lang	= $request->segment(1);
$locale = App::currentLocale();
$supportedLocales = config('app.supportedLocales');

if ($lang == $locale){
    $request->session()->put('locale', $lang);
    app()->setLocale($request->segment(1));
}
elseif (in_array($lang, $supportedLocales)){
    $request->session()->put('locale', $lang);
    app()->setLocale($request->segment(1));
    
}
else{
    return redirect(App::currentLocale());
}

Similarly, if you are able to do it write, your setLocale code will look same as below image.

Locale Middleware Laravel Code Example
Locale Middleware Laravel Code Example

2.3 Add Laravel Kernel Middleware Groups

Hence, we need this operation to run on every request. So, we need to add Middleware in app/http/Kernel.php under protected $routeMiddleware, in the end. Thus, only copy 'setlocale' => \App\Http\Middleware\SetLocale::class, code and paste in the end of $routeMiddleware in app/http/Kernel.php, similar to below.

    protected $routeMiddleware = [
        'auth' => \App\Http\Middleware\Authenticate::class,
        'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
        'auth.session' => \Illuminate\Session\Middleware\AuthenticateSession::class,
        'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
        'can' => \Illuminate\Auth\Middleware\Authorize::class,
        'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
        'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
        'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
        'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
        'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
	'setlocale' => \App\Http\Middleware\SetLocale::class,
    ];

2.4 Middleware Route Laravel Localization

Finally, you can add below route to use setLocale Middleware with your all routes within Route Group.

# routes/web.php
Route::group(['prefix' => '{locale}', 'where' => ['locale' => '[a-zA-Z]{2}'], 'middleware' => 'setlocale'], function() {
	Route::get('/', function () {
	  return view('welcome');
	});
});

3. Controller Method: Laravel 9 Localization

Finally, if you don’t want to use Laravel Middleware in Laravel localization, then simply use Laravel Controller for Laravel localization. In fact, you need to enhance

3.1 Create Controller in Laravel 9

Meanwhile, you need to create a controller that we will use switch the desired language in Laravel app. So, let’s execute the command below to create a controller.

PHP artisan make:controller LanguageController

Afterwards, you need to add Laravel localization routes to manage Laravel localization with Laravel controller.

3.2 Laravel Localization Routes for Controller

Of course, We need to update our Laravel localization routes to work with controller based localization. Please use the code below for controller based Laravel localization.

# routes/web.php
Route::get('/', function () {
    return redirect(app()->getLocale());
});
Route::group(['prefix' => '{locale}'], function() {
    Route::get('/', [LanguageController::class, 'index']);
});

In fact, if you review the code above, we have used half of the code exactly same as we used method 1, under the heading 1.1 of this Laravel tutorial. So, let me explain the route::group in the above code example. Here, we are using locale prefix but instead of the Laravel Middleware, we are using a route to use LanguageController.

3.3 Laravel Localization from Controller

Similar to Middleware, we need to check and confirm the available locale in our Laravel config/app.php file. So, before using the requested locale, we need to confirm it and then redirect it from LanguageController. Let’s move to LanguageController and here is the code.

$lang	= $request->segment(1);
$locale = App::currentLocale();
$supportedLocales = config('app.supportedLocales');
$appLocale	= $request->session()->get('appLocale');

if ($lang == $appLocale){
	$request->session()->put('appLocale', $lang);
	app()->setLocale($request->segment(1));
	//echo "Rizwan Ranjha: Language Same Hey Bhai !!!";exit;
}
elseif (in_array($lang, $supportedLocales)){
	$request->session()->put('appLocale', $lang);
	app()->setLocale($request->segment(1));
	//echo "Rizwan Ranjha: Language Labh Gayi Hey Bhai !!!";exit;
	
}
else{
	$request->session()->put('appLocale', $locale);
	return redirect(App::currentLocale());
	//echo "Rizwan Ranjha: Pehli Language main Kiya Takleef Hey?";exit;
}
return view('welcome');
Laravel Localization Routes for Controller

Translation For Specific Language In Laravel 9

For example, I am using English and Urdu language for this tutorial. I am comfortable to speak English and Urdu, so please bear with me and you may use any language you like to use. Secondly, I am using short keys to display translation strings in my Laravel app. Typically, translation strings are stored in files within the /lang directory. Therefore, I also created two files name translation.php in /en and also in /ur folder under /lang folder resides on root Laravel project, same as .

/lang
    /en
       translation.php
    /ur
       translation.php

Furthermore, You must consider these things.

  • Firstly, Create language folder in /lang directory, based on the locale format in config\app.php.
  • Secondly, create translation.php file your newly created or existing /lang/en folder.
  • Add keyed strings with names, as much as data your like to display.
    • I am using ‘title‘ and ‘message‘ for this Laravel tutorial.

Despite the lengthy Laravel tutorial, I am pasting the code below for English translation.php file.

# /lang/en/translation.php
<?php
return [
    'title' => "Documentation",
    'message' => "Laravel has wonderful, thorough documentation covering every aspect of the framework. Whether you are new to the framework or have previous experience with Laravel, we recommend reading all of the documentation from beginning to end.",
];

Load Translation Base on the Locale

In fact, I removed everything form default welcome.blad.php view file and only kept the following code in file to use language translation based on the locale. Further, you can see that I am using the following in code below.

  1. Firstly, I replaced Documentation with {{__(‘translation.title’)}} to use key strings used in translation.php files resides in /lang/en and also /lang/ur folders.
  2. Secondly, I replaced content with {{__(‘translation.message’)}} to use key strings used in translation.php files for all languages.
<div class="mt-8 bg-white dark:bg-gray-800 overflow-hidden shadow sm:rounded-lg">
    <div class="grid grid-cols-1">
        <div class="p-6">
            <div class="flex items-center">
                <svg fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="2" viewBox="0 0 24 24" class="w-8 h-8 text-gray-500"><path d="M12 6.253v13m0-13C10.832 5.477 9.246 5 7.5 5S4.168 5.477 3 6.253v13C4.168 18.477 5.754 18 7.5 18s3.332.477 4.5 1.253m0-13C13.168 5.477 14.754 5 16.5 5c1.747 0 3.332.477 4.5 1.253v13C19.832 18.477 18.247 18 16.5 18c-1.746 0-3.332.477-4.5 1.253"></path></svg>
                <div class="ml-4 text-lg leading-7 font-semibold"><a href="https://laravel.com/docs" class="underline text-gray-900 dark:text-white">{{__('translation.title')}}</a></div>
            </div>
            <div class="ml-12">
                <div class="mt-2 text-gray-600 dark:text-gray-400 text-sm">
                {{__('translation.message')}}
                </div>
            </div>
        </div>
    </div>
</div>

Laravel English Language Translation

Hence, you can see Laravel English Language Translation in this image.

Laravel English Language Translation

Laravel Urdu Language Translation

Hence, you can see Laravel English Language Translation in this image.

Laravel Urdu Language Translation

Missing required parameter for [Route: login] [URI: {locale}/login]

Additionally and equally important, after configuring Laravel localization in your Laravel 9 app, you may face Missing required parameter for [Route: login] [URI: {locale}/login] error in your view blade. Please read this reference Laravel 9 tutorial, for missing required parameter for [Route: login] [URI: {locale}/login] error. In fact, we need to use {{ route(‘login’, app()->getLocale()) }} for login and app()->getLocale() with all other routes.

Reference Documentation

Share

You may also like...