I am using Laravel 8 and I want to translate a website. As I have a lot of translations to do, I will use the "translations strings as key" (please see Laravel documentation).
I can use the following two methods in my Blade files.
{{ __('A propos') }}
OR
@lang('A propos')
My question is: what method do you use and why?
I'd really prefer using the __ helper function. If you go in-depth then you will find this helper function pretty cool in terms of its functionality and flexibility. Other than the translation string it receives 2 other parameters. One is replace[] and other is locale.
if (! function_exists('__')) {
/**
* Translate the given message.
*
* @param string|null $key
* @param array $replace
* @param string|null $locale
* @return string|array|null
*/
function __($key = null, $replace = [], $locale = null)
{
if (is_null($key)) {
return $key;
}
return trans($key, $replace, $locale);
}
}
So we can use this function to perform translation using the key and in bonus also to replace the translation with the values passed in 2nd parameter. Not only that, but we also have the option to specify in which language we need the translation in the 3rd parameter.
Secondly, we can use this function anywhere in the project either in Laravel Controllers , views etc.
On the other side, we have the blade directive @lang(). I couldn't find its definition anywhere in the vendor but I'm sure that you can only use this in your blade templates. Further it has no replace[] and locale parameter flexibility just like the __() helper function.
At the end of the debate, I'll really choose __() helper function because it is flexible, reusable and good documented.