Laravel on Laravel Localization

localization feature of laravel supports different language to be used in application. you need to store all the strings of different language in a file and these files are stored at resources/views directory. you should create a separate directory for each supported language. all the language files should return an array of keyed strings as shown below.

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

example

step 1 − create 3 files for languages − english, french, and german. save english file at resources/lang/en/lang.php

<?php
   return [
      'msg' => 'laravel internationalization example.'
   ];
?>

step 2 − save french file at resources/lang/fr/lang.php.

<?php
   return [
      'msg' => 'exemple laravel internationalisation.'
   ];
?>

step 3 − save german file at resources/lang/de/lang.php.

<?php
   return [
      'msg' => 'laravel internationalisierung beispiel.' 
   ];
?>

step 4 − create a controller called localizationcontroller by executing the following command.

php artisan make:controller localizationcontroller --plain

step 5 − after successful execution, you will receive the following output −

localizationcontroller

step 6 − copy the following code to 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/routes.php file. notice that we are passing {locale} argument after localization/ which we will use to see output in different language.

app/http/routes.php

route::get('localization/{locale}','localizationcontroller@index');

step 8 − now, let us visit the different urls to see all different languages. execute the below url to see output in english language.

http://localhost:8000/localization/en

step 9 − the output will appear as shown in the following image.

laravel internationalization

step 10 − execute the below url to see output in french language.

http://localhost:8000/localization/fr

step 11 − the output will appear as shown in the following image.

french example

step 12 − execute the below url to see output in german language

http://localhost:8000/localization/de

step 13 − the output will appear as shown in the following image.

german example