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

FallOutBoi's avatar

Translation using database table

Hi, i've made a table called categories where user can insert category name in three different languages and its url alias. It looks like this

id|name_us|name_hy|name_ru|url_alias|created_at|updated_at|

I want to use these translations in home page where categories will be shown, but i don't how to approach this more efficiently. I was thinking about checking language in controller but i don't know if it will be correct. I also have the lang files if needed. I was also wondering if i could just put these names in lang file.

0 likes
2 replies
bobbybouwmann's avatar
Level 88

For accessing a translation from the database you should probably make an accessor. So something like this

// app/Category.php

public function getNameAttribute()
{
    $language = app()->getLocale();

    return $this->{'name_' . $language};
}

Then in your view you can simply do this

{{ $category->name }}

Documentation: https://laravel.com/docs/5.8/eloquent-mutators#defining-an-accessor

The only think you need to do is make sure you set the correct locale. You can do this in a middleware as an example

1 like

Please or to participate in this conversation.