Laravel - Localization

Laravel - Localization

The localization feature of Laravel supports a different language to be used in the application. You need to store all strings in different languages ​​in a file and these files are stored in resources/views directory . You must create a separate directory for each supported language. All language files must return an array of strings with keys, as shown below.

<? php
 return [ 'welcome' => 'Welcome to the application' ]; 
     

example

Step 1 - Create 3 files for languages ​​- English, French and German . Save the english file in resources/lang/en/lang.php

<?php
   return [
      'msg' => 'Laravel Internationalization example.'
   ];
?>

Step 2 − Save the french file in resources/lang/fr/lang.php .

<?php
   return [
      'msg' => 'Example Laravel internationalization.'
   ];
?>

Step 3 − Save the german file in resources/lang/de/lang.php .

<?php
   return [
      'msg' => 'Laravel Internationalisierung Beispiel.' 
   ];
?>

Step 4 − Create a controller named LocalizationController by running the following command.

php artisan make:controller LocalizationController --plain

Step 5 − Upon successful execution, you will get the following output −

Step 6 - Copy the following code to a file

app/Http/Controllers/LocalizationController.php

app/Http/Controllers/LocalizationController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class LocalizationController extends Controller {
   public function index(Request $request,$locale) {
      //set's application's locale
      app()->setLocale($locale);
      
      //Gets the translated message and displays it
      echo trans('lang.msg');
   }
}

Step 7 − Add a route for LocalizationController in app/Http/rout.php file . Note that we are passing the {locale} argument after the localization / which we will use to see the output in another language.

app/http/routes.php

Route::get('localization/{locale}','LocalizationController@index');

Step 8 − Now let's visit different URLs to see all the different languages. Execute the URL below to see the output in English.

http://localhost:8000/localization/en

Step 9 − The output will look as shown in the following image.

Step 10 − Execute the URL below to see the output in French.

http://localhost:8000/localization/fr

Step 11 − The output will look as shown in the following image.

Step 12 - Execute the URL below to see the output in German

http://localhost:8000/localization/de

Step 13 − The output will look as shown in the following image.