You can get this approach by changing the default __
helper by:
use Illuminate\Support\Arr;
function __($key = null, $replace = [], $locale = null)
{
// Default behavior
if (is_null($key)) return $key;
if (trans()->has($key)) return trans($key, $replace, $locale);
// Search in .json file
$search = Arr::get(trans()->get('*'), $key);
if ($search !== null) return $search;
// Return .json fallback
$fallback = Arr::get(trans()->get('*', [], config('app.fallback_locale')), $key);
if ($fallback !== null) return $fallback;
// Return key name if not found
else return $key;
}
Creating custom bootstrap helpers
if you dont know how to change the default helper, create a file with any name (ex: bootstrap/helpers.php
), then in the file public/index.php
add this line just before 'Register The Auto Loader'
/*
|--------------------------------------------------------------------------
| Register Custom Helpers
|------------------------------------------------------------------------
*/
require __DIR__.'/../bootstrap/helpers.php';
(Optional) Variables feature
if you also want to use the Variables feature, just like __(welcome.user, ['user'=>'david'])
you must create a new helper on that file:
use Illuminate\Support\Str;
function trans_replacements($line, array $replace)
{
if (empty($replace)) return $line;
$shouldReplace = [];
foreach ($replace as $key => $value) {
$shouldReplace[':'.Str::ucfirst($key)] = Str::ucfirst($value);
$shouldReplace[':'.Str::upper($key)] = Str::upper($value);
$shouldReplace[':'.$key] = $value;
}
return strtr($line, $shouldReplace);
}
and then replace return $search
with trans_replacements($search, $replace)
and return $fallback
with trans_replacements($fallback, $replace)
(Optional) Countable feature
for Countable feature (ex: 'an apple|many apples'
), is the same process, just add this helper:
use Illuminate\Support\Facades\App;
function trans_choice($key, $number, array $replace = [], $locale = null)
{
// Get message
$message = __($key, $replace, $locale);
// If the given "number" is actually an array or countable we will simply count the
// number of elements in an instance.
if (is_array($number) || $number instanceof Countable)
$number = count($number);
$replace['count'] = $number;
return trans_replacements(
trans()->getSelector()->choose($message, $number, $locale = App::getLocale()),
$replace
);
}
Bootstrap Helpers File
here is the file, just in case: bendeckdavid/laravel_locale_nested_json