Framework: Laravel trans() not working only returns key

Created on 6 Oct 2017  路  5Comments  路  Source: laravel/framework

  • Laravel Version: 5.4
  • PHP Version: 7*

My directory looks like this:

majs

/resources
    /lang
        /en
            api.php

api.php looks like this:

<?php

return [
    'couldnotlogin' => 'Login failed, please check email and password',

];

But when I try

dd(trans('api.couldnotlogin'));

it will only output:

api.couldnotlogin

dd(App::getLocale());

returns en

other setting

'locale' => 'en',
'fallback_locale' => 'en',

I also tried dd(Lang::has('api.couldnotlogin', 'en')); which returns false
even dd(Lang::has('auth.failed', 'en')); returns false

What am I doing wrong?

Most helpful comment

Hold up, your lang shouldn't be nested under assets. It should be nested under resources.

screen shot 2017-10-06 at 3 14 42 pm

All 5 comments

The trans helper doesn't have a fallback if your key doesn't exist in the translation files. You could try creating trans_fb helper where you can specify a default return value:

/**
 * Makes translation fall back to specified value if definition does not exist
 *
 * @param string $key
 * @param null|string $fallback
 * @param null|string $locale
 * @param array|null $replace
 *
 * @return array|\Illuminate\Contracts\Translation\Translator|null|string
 */
function trans_fb(string $key, ?string $fallback = null, ?string $locale = null, ?array $replace = [])
{
    if (app(Illuminate\Contracts\Translation\Translator::class)->has($key, $locale)) {
        return trans($key, $replace, $locale);
    }

    return $fallback;
}

@jpcaparas but my file/key do exist, dd(trans('api.couldnotlogin')); should output _Login failed, please check email and password_

majs

That's actually odd. It should work based on your directory structure. Have you tried running php artisan clear-compiled?

Hold up, your lang shouldn't be nested under assets. It should be nested under resources.

screen shot 2017-10-06 at 3 14 42 pm

@jpcaparas Your right! It should be nested under resources Thanks you so much for seeing it!

Was this page helpful?
0 / 5 - 0 ratings