Is there a difference between Lang::get('locale') and __('locale') in Laravel?
Asked Answered
B

1

5

In Laravel 5.7 the docs say to use the following syntax to retrieve locales

{{ __ ('my.locale')}}

but I noticed

{{Lang::get('my.locale')}}

works too, and it's in fact what was also used in previous versions.

Is there a fundamental difference between this two, or just the syntax changed?

Broncobuster answered 8/11, 2018 at 13:53 Comment(0)
F
13

The main difference is that __() and @lang will check for json translation files in addition to your php language files. Other than that, the syntax hasn't changed; they all defer to the same \Illuminate\Translation\Translator::get() method eventually.

These will all work from a Blade view:

@lang('...')
{{ __('...') }}
{{ trans('...') }}
{{ Lang::trans('...') }}
{{ Lang::get('...') }}
{{ app('translator')->get('...') }}

If you use the @lang Blade directive, keep in mind that it doesn't escape htmlentities, which means your translation strings would need to be stored in their escaped form (e.g. &lt;&gt; instead of <>). None of the other functions escape htmlentities either, but using @lang is the only option in that list that doesn't pass the string through the handlebars {{ }}, which is where the escape function is called. It may not be common to have html special characters in a translation string, and translation strings don't usually come from user input (so cross-site scripting isn't an issue), but it's worth knowing.


If you want to dive deeper, this is the difference with __() (as of Laravel 5.8):

/**
 * Translate the given message.
 *
 * @param  string  $key
 * @param  array  $replace
 * @param  string  $locale
 * @return string|array|null
 */
function __($key, $replace = [], $locale = null)
{
    return app('translator')->getFromJson($key, $replace, $locale);
}

You can see it's using getFromJson() instead of get(). However, getFromJson() falls back to get() if it didn't find anything in your json files:

// If we can't find a translation for the JSON key, we will attempt to translate it
// using the typical translation file. This way developers can always just use a
// helper such as __ instead of having to pick between trans or __ with views.
if (! isset($line)) {
    $fallback = $this->get($key, $replace, $locale);

    if ($fallback !== $key) {
        return $fallback;
    }
}

Then there's trans(), which is nothing more than an alias for get():

public function trans($key, array $replace = [], $locale = null)
{
    return $this->get($key, $replace, $locale);
}
Fluorocarbon answered 10/11, 2018 at 8:38 Comment(1)
Alternative to @lang would be {!! trans() !!} in case you need HTML-support in the strings (no escape, security risk, if the input is unsafe)Smote

© 2022 - 2024 — McMap. All rights reserved.