Laravel Localization · · 10 min read

@lang vs __() vs trans() in Laravel: What Each One Actually Does

Search a Laravel codebase that has been around for a few years and you'll find every translation style at once: {{ __('auth.failed') }} in one view, @lang('auth.failed') in the next, trans('auth.failed') in a controller and trans_choice() somewhere in a mailable. They all print the same text, so it's tempting to treat them as synonyms.

They mostly are, but there's one difference that matters for security, plus a few edge cases around arrays, missing keys and Lang::has that trip people up. Everything below was checked against the Laravel 12 framework source and run in Tinker.

They all call the same method

Here are the helpers from Illuminate/Foundation/helpers.php, trimmed:

function trans($key = null, $replace = [], $locale = null)
{
    if (is_null($key)) {
        return app('translator');
    }

    return app('translator')->get($key, $replace, $locale);
}

function __($key = null, $replace = [], $locale = null)
{
    if (is_null($key)) {
        return $key;
    }

    return trans($key, $replace, $locale);
}

__() is a thin wrapper around trans(), and trans() calls Translator::get(). The Lang facade (Lang::get()) calls the same method too. Give them a key and they return the same thing. The only difference shows up when you pass nothing: trans() returns the translator instance, and __() returns null.

trans_choice($key, $number) calls Translator::choice(), which looks up the line through get() and then picks the plural form for $number.

So in PHP code (controllers, jobs, notifications), choosing between __() and trans() comes down to style. In Blade, it matters more.

What @lang compiles to

The Blade directives are defined in Illuminate/View/Compilers/Concerns/CompilesTranslations.php. Here's what each one compiles to in Laravel 12, taken from Blade::compileString():

// @lang('demo.greeting', ['name' => $x])
<?php echo app('translator')->get('demo.greeting', ['name' => $x]); ?>

// {{ __('demo.greeting', ['name' => $x]) }}
<?php echo e(__('demo.greeting', ['name' => $x])); ?>

// @choice('demo.apples', 3)
<?php echo app('translator')->choice('demo.apples', 3); ?>

The difference is e(). {{ }} runs the result through htmlspecialchars. @lang and @choice echo the result directly, which makes @lang('key') the same as {!! __('key') !!}.

That has two consequences.

Replacement values are not escaped. With a line 'greeting' => 'Hola, :name' and a user-controlled name:

@lang('demo.greeting', ['name' => $user->name])
{{-- If name is <script>x</script>, renders: Hola, <script>x</script> --}}

{{ __('demo.greeting', ['name' => $user->name]) }}
{{-- Renders: Hola, &lt;script&gt;x&lt;/script&gt; --}}

Laravel's placeholder replacement is a plain strtr(), so nothing escapes the value on the way in. If the value comes from a user, @lang with replacements is an XSS hole.

Translations containing HTML render as HTML. This is why some teams use @lang on purpose: a line like 'terms' => 'I accept the <a href="/terms">terms</a>' displays a working link with @lang and literal tags with {{ __() }}. That's fine when the line is trusted, but every person who can edit a translation can now inject markup into your page. If translators or an external tool write to your lang files, you've extended your trust boundary to them.

A lot of tutorials describe @lang as "the Blade version of __()." Functionally it's the Blade version of {!! __() !!}.

The @lang block form nobody uses

The same compiler method has a second branch. Called with no arguments, or with an array as the first argument, @lang starts a block and treats the trimmed body as the key:

@lang(['name' => 'Ana'])
    demo.greeting
@endlang
{{-- Renders: Hola, Ana --}}

It compiles to $__env->startTranslation([...]) plus output buffering, and @endlang echoes the result, again without escaping. It works, but code scanners and IDE plugins that look for __('...') patterns won't see the key. Treat it as a curiosity.

JSON keys and PHP keys go through the same lookup

There's a common belief that __() is for JSON files and trans() is for PHP files. The source says otherwise. Translator::get() always checks the JSON file for the current locale first, using the whole string as the key:

$this->load('*', '*', $locale);

$line = $this->loaded['*']['*'][$locale][$key] ?? null;

If there's no match, it splits the key on dots into group and item and searches lang/{locale}/{group}.php, first in the current locale and then in the fallback locale. Every helper and directive goes through this order, so @lang('Welcome back, :name') reads lang/es.json exactly like __() does.

// lang/es.json: {"Welcome back, :name": "Bienvenido de nuevo, :name"}
__('Welcome back, :name', ['name' => 'ana']);   // "Bienvenido de nuevo, ana"

// lang/es/demo.php: ['greeting' => 'Hola, :name']
trans('demo.greeting', ['name' => 'ana']);      // "Hola, ana"

Replacements also respect case: :name, :Name and :NAME in the line receive the value as given, capitalized, or uppercased. If you're deciding between the two file formats, we compared them in detail in JSON vs PHP lang files.

They can return arrays

The __() return type is string|array|null, and the array case is real. If the key points at a group or a nested array, you get the whole array back, with placeholders replaced in every value:

// lang/es/demo.php: ['nested' => ['a' => 'A', 'b' => 'B']]
__('demo.nested');   // ['a' => 'A', 'b' => 'B']

That's useful in PHP. For example, __('validation.attributes') gives you every field label. In Blade it fails:

{{ __('demo.nested') }}
{{-- ViewException: htmlspecialchars(): Argument #1 ($string) must be of type string, array given --}}

The usual cause is a key that has turned into a parent, like profile.title gaining profile.title.short in a refactor. With @lang the failure is different (PHP's "Array to string conversion"), but the page still breaks. trans_choice() is typed to return a string and always does.

What happens when a key is missing

When a key isn't found in the current locale or the fallback locale, get() returns the key itself:

__('demo.missing');      // "demo.missing"
__('demo.only_en');      // "English only" (found in the fallback locale)
__('Some new sentence'); // "Some new sentence"

This is the practical difference between the two key styles. A missing PHP key shows up as demo.missing on the page, which is ugly but easy to notice. A missing JSON key renders the English source sentence, so a Spanish page with half its JSON keys missing looks fine to anyone who doesn't read Spanish. The fallback locale has the same effect for PHP keys: if English has the key and Spanish doesn't, the visitor silently gets English.

Laravel 12 lets you hook into the miss so you can log it:

// AppServiceProvider::boot()
Lang::handleMissingKeysUsing(function (string $key, array $replace, ?string $locale, bool $fallback) {
    Log::warning('Missing translation', ['key' => $key, 'locale' => $locale]);

    return $key;
});

Read the condition carefully. The callback only runs when no locale, fallback included, has the line. A key that exists in English and not in Spanish never fires it. To catch that drift, compare key sets across locales in CI. We cover that in testing Laravel localization with Pest.

Lang::has and its fallback trap

Lang::has() looks like the right way to ask whether a translation exists. Its signature is has($key, $locale = null, $fallback = true), and the default matters:

app()->setLocale('es');

Lang::has('demo.only_en');          // true, because English has it
Lang::hasForLocale('demo.only_en'); // false, Spanish doesn't
Lang::has('demo.missing');          // false
Lang::has('Welcome back, :name');   // true (JSON key present in es.json)

If you're checking "is this translated into the visitor's language," use Lang::hasForLocale() or pass false as the third argument. has() answers a different question: "will something other than the raw key come back?"

There's one more detail in the implementation. For PHP keys, has() works by calling get() and checking that the result isn't the key. While it does that, it turns off the missing-key handler, so Lang::has() checks won't flood the log you set up above.

trans_choice and @choice

For plurals, use trans_choice() in PHP and either {{ trans_choice() }} or @choice in Blade. @choice has the same escaping caveat as @lang.

// lang/es/demo.php
'apples' => '{0} No hay manzanas|{1} Una manzana|[2,*] :count manzanas',
trans_choice('demo.apples', 0);         // "No hay manzanas"
trans_choice('demo.apples', 1);         // "Una manzana"
trans_choice('demo.apples', [1, 2, 3]); // "3 manzanas" (arrays and Countables are counted)

:count is filled in automatically unless you pass your own. One quirk from the source: choice() checks whether the key exists in the current locale, and if it doesn't, it uses the fallback locale's line and the fallback locale's plural rules. A plural key missing from Polish or Russian doesn't just show English text. It also applies English's two-form plural logic to it. The full rules are in trans_choice and pluralization, and you can try a pipe string against real CLDR plural categories with the plural tester.

Which one to standardize on

This is the convention we'd recommend for a Laravel 12 codebase:

  • Blade: {{ __('key') }} for everything. It escapes by default, so replacement values are safe.
  • Trusted HTML in a translation: {!! __('key') !!}. It does what @lang does, but the {!! !!} makes it obvious in code review that the output is raw. Never pass user input as a replacement here.
  • Plurals: {{ trans_choice('key', $count) }} in views, trans_choice() in PHP. Skip @choice for the same reason as @lang.
  • PHP code: __(). It matches the views, which keeps one pattern to grep for and one pattern for extraction tools to parse.
  • Existence checks: Lang::hasForLocale() when you mean "translated into this language."
  • Avoid: @lang, the @lang ... @endlang block, and calling trans() without arguments to get the translator. If you need the translator, inject Illuminate\Contracts\Translation\Translator or use the Lang facade.

The official localization docs use __() throughout, so this convention also matches what new team members will have read.

Migrating is mechanical. A search for @lang( and @choice( finds every call, and each one becomes {{ __(...) }} or {{ trans_choice(...) }}. The exception is a line that intentionally contains HTML: switch those to {!! !!} and check where their replacement values come from. While you're in the views, run the Blade scanner to catch strings that never went through a helper at all, since a hardcoded string is a bigger problem than the wrong helper. We cover that in finding hardcoded text. Livewire components follow the same rules; see translations in Livewire 3.

Summary

  • __(), trans(), Lang::get(), @lang and the @lang block all call Translator::get(). trans_choice() and @choice call Translator::choice().
  • @lang(...) compiles to <?php echo app('translator')->get(...); ?> with no e(). It's unescaped, the same as {!! __() !!}. @choice is unescaped too.
  • Every helper checks the JSON file first and then PHP group files. The choice of helper doesn't depend on the file format.
  • Keys that point to arrays return arrays, and {{ }} throws when it gets one.
  • Missing keys return the key itself. For JSON keys, that means the English sentence, which is easy to miss.
  • Lang::has() counts the fallback locale. Lang::hasForLocale() doesn't.
  • Standardize on {{ __() }} and {{ trans_choice() }}, and use {!! !!} deliberately when you need raw HTML.

Once the helper calls are consistent, the remaining problem is the text behind the keys and who is allowed to change it. LangSyncer lets non-developers edit translations and publish them live without a deploy, and shows per-language coverage so a missing key doesn't silently fall back to English.

More on Laravel Localization

All Laravel Localization articles →

We'd like to use analytics and marketing cookies to understand how the site is used. They stay off unless you accept them. Cookie Policy