Top
/resources
/lang
/en
lang.php
/es
lang.php
All language files return an array of keyed strings. For example:
<?php
return[
'welcome' => 'Welcome to our application',
];
?>
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:
//Language Change
Route::get('lang/{locale}', function ($locale) {
if (! in_array($locale, ['en', 'de', 'es','fr','pt', 'cn', 'ae'])) {
abort(400);
}
Session()->put('locale', $locale);
Session::get('locale');
return redirect()->back();
})->name('lang');
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',
Next up, we are going to create a middleware for dynamically changing the language.
php artisan make:middleware Localization
App\Http\Middleware\Localization.php
namespace App\Http\Middleware;
use Closure;
use Session;
use Illuminate\Http\Request;
use Illuminate\Foundation\Application;
class Localization
{
public function __construct(Application $app, Request $request) {
$this->app = $app;
$this->request = $request;
}
public function handle($request, Closure $next)
{
$this->app->setLocale(session()->get('locale') ?? 'en');
return $next($request);
}
}
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/lang.php language file:
welcome.blade.php
{{ __('lang.welcome') }}
{{ __('I love programming.') }}
If you are using the Blade templating engine, you may use the {{ }} syntax to echo the translation string or use the @lang directive:
{{ __('lang.welcome') }}
@lang('lang.welcome')
{{ trans('lang.welcome') }}
If the specified translation string does not exist, the __ function will return the translation string key. So, using the example above, the __ function would return lang.welcome if the translation string does not exist.
Note: The @lang directive does not escape any output. You are fully responsible for escaping your own output when using this directive.