Let's say you have a Login page with the language prefix in URL: /en/login
and /fr/login
. To show French/English texts on the Login page, you need to do these things:
1. Activate the Locale Language form URL
Somewhere in your code you should have this:
App::setLocale(request()->segment(1));
One of the ways to do it is to have a special Middleware:
php artisan make:middleware SetLocale
Then inside that Middleware:
app/Http/Middleware/SetLocaleMiddleware.php:
use Illuminate\Support\Facades\App; class SetLocaleMiddleware{ public function handle(Request $request, Closure $next) { App::setLocale($request->segment(1)); return $next($request); }}
And then you need to assign that Middleware either to specific routes, or globally for all routes:
app/Http/Kernel.php:
class Kernel extends HttpKernel{ /** * The application's global HTTP middleware stack. * * These middleware are run during every request to your application. * * @var array<int, class-string|string> */ protected $middleware = [ // \App\Http\Middleware\TrustHosts::class, \App\Http\Middleware\TrustProxies::class, // ... \App\Http\Middleware\SetLocaleMiddleware::class, ]; // ...}
2. Define Translation Strings and Values
You should create two files:
- /lang/en/translations.php
- /lang/fr/translations.php
Notice: on Laravel 8 and earlier versions, the folder should be /resources/lang
instead of /lang
And then define the key-value pairs with the actual translations inside.
/lang/en/translations.php:
return [ 'email' => 'Email', 'password' => 'Password', // ...];
/lang/fr/translations.php:
return [ 'email' => 'E-mail', 'password' => 'Le mot de passe', // ...];
3. Show Translations in Blade
Finally, when the locale is set and translations are specified, you can show them in Blade, like this:
{{ __('translations.email') }}:<input type="email" name="email" /> {{ __('translations.password') }}:<input type="password" name="password" />
Is there article that shows language based database records based on language selected?
You can also use the @lang blade directive instead of (''), for some IDEs it is better when autocompletion is necessary.
Is it better to have one big php lang file or multiple more files? Does it affect performance anyhow? How can we cache these translations?
I prefer multiple lang files, by topic, as Laravel suggests by default, with a separate file on validation, auth, etc.
I don't think they need to be cached, as they don't come from the DB anyway.