Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Francesco's avatar

Retrieve translation string key from database

Hi,

I would ask you if the following text translation management can be feasible or not in Laravel. I know that the best practice tell us to create a corresponding text table but for some reason I would try to keep these translation only in the json file.

Let say we have a table "soil_type", where each row define some property/values of a kind of soil. This is not a table that will be edited by the user. It is a "fixed" table used just for backend logic. And it will not need to be changed/adapted.

I will have:

  • ID
  • Translation key
  • value 1
  • value 2 etc etc

My intention is to put in this table the translation key of each record. When i want to echo or use this translation I will pass a variable e not a string to the various functions used for managing translation:

$trans_key = 'Sand'; //actually is retrieved from database.

echo __($trans_key);

or in blade

{{ __($trans_key) }}

@lang($trans_key)

0 likes
3 replies
Swaz's avatar

@Francesco I've done something like this in the past. I ended up just putting a get method on the model. Then you can use it like normal and it will always be in the correct locale.

Example:

// db
Types
id | name
// model
class Type extends Model
{
    public function getNameAttribute()
    {   
        return __($this->name);
    }
}
// view
{{ $type->name }} // 'Translated Name'
1 like
Francesco's avatar

you assign the result of getNameAttribute() to the name field of the model, right ?

and in the name field you put the key translation you find in json, correct ?

Swaz's avatar
Swaz
Best Answer
Level 20

Correct.

The name field would be the name in my default launguage (english). Which would end up being the translation key if you are using the translation strings helper __('Tree'). You would still need to set the apps locale somewhere App::setLocale('fr'), like in a route group or middleware.

// db
Types
id | name
1  | Tree
2  | Sand
3  | Water
// resources/lang/fr.json
{
    "Tree": "Arbre",
    "Sand": "Le sable",
    "Water": "Eau",
}
App::setLocale('en');
{{ $type->name }} // 'Tree'

App::setLocale('fr');
{{ $type->name }} // 'Arbre'

Please or to participate in this conversation.