Laravel Multi-Language: Show Translated Texts in Blade

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" />
avatar
Loganathan Natarajan

Is there article that shows language based database records based on language selected?

avatar

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?

avatar

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.

Like our articles?

Become a Premium Member for $129/year or $29/month
What else you will get:
  • 59 courses (1056 lessons, total 44 h 09 min)
  • 78 long-form tutorials (one new every week)
  • access to project repositories
  • access to private Discord

Recent Premium Tutorials