Recently, in the Mastering Laravel community, someone was asking how to reference a language key from another value inside an array-based language file.
For example, let's say you had a language file that had a common word like "profile", which you wanted to refer to in other translated values:
// lang/en/account.php
return [
'profile' => 'profile',
'update_profile' => 'Update your profile',
'incomplete_profile' => 'Your profile is incomplete. Please add more details.',
'welcome_profile' => 'Welcome to your new profile.',
];
Is there a way to reference the profile
key and not have to repeat the word in other values?
My first thought was something like this:
// lang/en/account.php
return [
'profile' => 'profile',
'update_profile' => 'Update your ' . __('account.profile'),
'incomplete_profile' => 'Your ' . __('account.profile') . ' is incomplete. Please add more details.',
'welcome_profile' => 'Welcome to your new ' . __('account.profile') . '.',
];
But this will not work. The file would be called recursively and will end with a stack overflow error.
If profile
was in a separate file, it would work, but you'd have to be careful to never create a circular dependency.
I also considered using a const
in the file. It works, but these are in the global namespace, so as soon as you create a second language file, they'd collide.
After thinking about this a bit, I think the best solution I have right now is to use a placeholder in the language file and then replace it in the code:
// lang/en/account.php
return [
'profile' => 'profile',
'update_profile' => 'Update your :profile',
'incomplete_profile' => 'Your :profile is incomplete. Please add more details.',
'welcome_profile' => 'Welcome to your new :profile.',
];
// then when using these keys in your code
__('account.update_profile', ['profile' => __('account.profile')]);
It's a little more verbose, but it's clear what's happening, and it avoids the infinite recursion.
Here to help,
Joel
P.S. Want to ask me questions and inspire future tips? You can join the community as well.