Localization
Introduction
Laravel's
localization
features provide a convenient way to retrieve strings in
various languages, allowing you to easily support multiple
languages within your application. Language strings are
stored in files within the
resources/lang
directory. Within this directory
there should be a subdirectory for each language supported
by the application:
resources/
├── lang/
| ├── en/
| | ├── locale.php
| ├── de/
| | ├── locale.php
All language files return an array of keyed strings. For example:
<?php
return [
"Dashboard" => "Instrumententafel",
"Analytics" => "Analytics",
...
......
];
Configuring The Locale
The default language for your application is stored in the
config/app.php
configuration file. You may
modify this value to suit the needs of your application. You
may also change the active language at runtime using the
setLocale
method on the
App
facade:
Route::get('welcome/{locale}', function ($locale) {
App::setLocale($locale);
//
});
You may configure a "fallback language", which will be used
when the active language does not contain a given
translation string. Like the default language, the fallback
language is also configured in the
config/app.php
configuration file:
'fallback_locale' => 'en',
Defining Translation Strings
Typically, translation strings are stored in files within
the resources/lang
directory. Within this
directory there should be a subdirectory for each language
supported by the application:
Retrieving Translation Strings
You may retrieve lines from language files using the
__
helper function. The __
method
accepts the file and key of the translation string as its
first argument. For example, let's retrieve the welcome
translation string from the
resources/lang/en/locale.php
language file:
echo __('locale.welcome');
If you are using the Blade templating engine, you may use the {{ }} syntax to echo the translation string or use the @lang directive
{{ __('messages.welcome') }}
@lang('messages.welcome')
Now all set to work localization in simple project.
Localization in Frest Admin Template
In Frest Laravel, We provide a dropdown to switch language
you can find it in the navbar. How does it work? When we
select a language from dropdown-menu we call a Route which
calls a controller's function. Controller keeps the selected
language in session. We have created a middleware that sets
the localization value from the session variable. We set the
session's lifetime 30min in the .env
file. It
sounds a little messy. Let's find out how to do it.
We have to create a Controller to check selected language is available or not in our template and then save it to session variable. Run below command.
php artisan make:controller LanguageController
Use the below code in LanguageController
file
in App/Http/Controllers
.
<?php
namespace App\Http\Controllers;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
class LanguageController extends Controller
{
//
public function swap($locale){
// available language in template array
$availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt'];
// check for existing language
if(array_key_exists($locale,$availLocale)){
session()->put('locale',$locale);
}
return redirect()->back();
}
}
We have to define Route for language switching in routes/web.php file.
<?php
use App\Http\Controllers\LanguageController;
// locale Route
Route::get('lang/{locale}',[LanguageController::class,'swap']);
Now we need a middleware to set
app()->setLocale()
variable gloabaly. Run below
cammand to create a middleware.
php artisan make:middleware LocaleMiddleware
You can find this middleware in
App\Http\Middleware
<?php
namespace App\Http\Middleware;
use Closure;
class LocaleMiddleware
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// available language in template array
$availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt'];
// Locale is enabled and allowed to be change
if(session()->has('locale') && array_key_exists(session()->get('locale'),$availLocale)){
// Set the Laravel locale
app()->setLocale(session()->get('locale'));
}
return $next($request);
}
}
You must have to mention middleware in the
App\Http\kernel.php
file. Use the
\App\Http\Middleware\LocaleMiddleware::class,
line in kernel.php file.
protected $middlewareGroups = [
'web' => [
\App\Http\Middleware\LocaleMiddleware::class,
],
'api' => [
'throttle:60,1',
'bindings',
],
];
Now we have to set the view. We provide language switch dropdown in navabar.blade.php.
<a class="dropdown-toggle nav-link" id="dropdown-flag" href="javascript:void(0);" data-toggle="dropdown"
aria-haspopup="true" aria-expanded="false">
<i class="flag-icon flag-icon-us"></i>
<span class="selected-language">English</span>
</a>
<div class="dropdown-menu" aria-labelledby="dropdown-flag">
<a class="dropdown-item" href="{{url('lang/en')}}" data-language="en">
<i class="flag-icon flag-icon-us"></i>English
</a>
<a class="dropdown-item" href="{{url('lang/fr')}}" data-language="fr">
<i class="flag-icon flag-icon-fr"></i>French
</a>
<a class="dropdown-item" href="{{url('lang/de')}}" data-language="de">
<i class="flag-icon flag-icon-de"></i>German
</a>
<a class="dropdown-item" href="{{url('lang/pt')}}" data-language="pt">
<i class="flag-icon flag-icon-pt"></i>Portuguese
</a>
</div>
We need to retrieve lines from language files using the
__
helper function. The __
method
accepts the file and key of the translation string as its
first argument. We are using the Blade templating engine, We
use the {{ }}
syntax to echo the translation
string or use the @lang
directive:
Resources/views/panels
sidebar.blade.php
<ul class="navigation navigation-main" id="main-menu-navigation" data-menu="menu-navigation" data-icon-style="lines">
@if(!empty($menuData[0]) && isset($menuData[0]))
@foreach ($menuData[0]->menu as $menu)
@if(isset($menu->navheader))
<li class="navigation-header"><span>{{$menu->navheader}}</span></li>
@else
<li class="nav-item {{(request()->is($menu->url.'*')) ? 'active' : '' }}">
<a href="@if(isset($menu->url)){{asset($menu->url)}} @endif">
@if(isset($menu->icon))
<i class="menu-livicon" data-icon="{{$menu->icon}}"></i>
@endif
@if(isset($menu->name))
<span class="menu-title">{{ __('locale.'.$menu->name)}}</span>
@endif
@if(isset($menu->tag))
<span class="{{$menu->tagcustom}}">{{$menu->tag}}</span>
@endif
</a>
@if(isset($menu->submenu))
@include('panels.sidebar-submenu',['menu' => $menu->submenu])
@endif
</li>
@endif
@endforeach
@endif
</ul>
sidebar-submenu.blade.php
<ul class="menu-content">
@if (isset($menu))
@foreach ($menu as $submenu)
<li {{(request()->is($submenu->url.'*')) ? 'class=active' : '' }}>
<a href="@isset($submenu->url) {{asset($submenu->url)}} @endisset">
<i class="bx bx-right-arrow-alt"></i>
<span class="menu-item">{{ __('locale.'.$submenu->name)}}</span>
</a>
@if(isset($submenu->submenu))
@include('panels.sidebar-submenu',['menu'=>$submenu->submenu])
@endif
</li>
@endforeach
@endif
</ul>
How to add new language?
1: To add a new language in whole template first we need to create a locale.php file in resources/lang/ which return an array with key and value pair.
resources/lang/de/locale.php
<?php
return [
"Dashboard" => "Instrumententafel",
"Analytics" => "Analytics",
"eCommerce" => "eCommerce",
"Apps" => "Anwendungen",
"UI Elements" => "UI Elemente",
"Forms & Tables" => "Formulare und Tabellen",
"Pages" => "Seiten",
"Charts & Maps" => "Karten & Landkarten",
"Others" => "Andere",
"Email" => "Email",
2: Now we need to mention our new language in controller and middleware which we already created.
App/Http/Controllers/LanguageController.php
// available language in template array
$availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt']; //mention your new language as key and value pair.
App/Http/Middleware/LocaleMiddleware.php
// available language in template array
$availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt']; //mention your new language as key and value pair.
3: If you want to set your new language as default language using configuration variable then you'll need to do below changes.
App/Helpers/helpers.php
Add your new language in allOption array as key and value pair.
// All options available in the template
$allOptions = [
'defaultLanguage'=>array('en'=>'en','fr'=>'fr','de'=>'de','pt'=>'pt'),
];
4: Now you can set your new language as default of whole Template.
config/custom.php
<?php
return [
'custom' => [
'defaultLanguage'=>'en', //en(default)/de/pt/fr here are four optional language provided in theme
],
Your new language is successfully added, Now it's ready to use.
How to remove existing language?
1: To remove a existing language in whole template first we
need to delete language folder from
resources/lang/
.
resources/
├── lang/
| ├── en/
| | ├── locale.php
| ├── de/
| | ├── locale.php
2: Now we need to delete existing language in controller and middleware which is already created.
App/Http/Controllers/LanguageController.php
Remove your existing language from the availLocale array.
// available language in template array
$availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt'];
App/Http/Middleware/LocaleMiddleware.php
Remove your existing language from the availLocale array.
// available language in template array
$availLocale=['en'=>'en', 'fr'=>'fr','de'=>'de','pt'=>'pt'];
3: You also need to remove this language from helper.php file.
App/Helpers/helpers.php
Remove language from the allOption array.
// All options available in the template
$allOptions = [
'defaultLanguage'=>array('en'=>'en','fr'=>'fr','de'=>'de','pt'=>'pt'),
];
Now existing language has been removed from whole template.