I haven't created page with translations in Laravel yet, but If I were you, I would create helper method for this and I would use something like that in my template:
<h1>{{ trtx('title') }}</h1>
{!! trtx('text') !!}
This way, you would have quite clean code in your template without hardcoding way of creating labels.
Just a sample implementation for this:
-
Create app/helpers/functions.php
file:
<?php
function trtx($title, $locale = null)
{
if ($locale == null) {
$locale = App::getLocale();
}
$trans = App::make('App\Services\Translator');
return $trans->get($title . '_' . $locale);
}
-
Create app/Services/Translator.php
file:
<?php
namespace App\Services;
class Translator
{
public function get($text)
{
return "This is translated text for " . $text;
}
}
-
In app/Providers/AppServiceProvider.php
in register
function add:
$this->app->singleton(
'App\Services\Translator',
'App\Services\Translator'
);
-
In composer.json
file add to autoload
section loading your helper file, so it should look like this:
"autoload": {
"classmap": [
"database"
],
"psr-4": {
"App\\": "app/"
},
"files": [
"app/Helpers/functions.php"
]
},
Run in console composer dump-autoload
and then run in console php artisan clear-compiled
Now it should work, if you put in your template for example:
{{ trtx('title') }} {{ trtx('title', 'fr') }}
you will get:
This is translated text for title_en This is translated text for title_fr
Of course now you should implement in Translator
class the real way you get translation from database. Of course there is no point to use DB for translations all the time. You should cache table where you have translations because if you will run query each time you want to display translation it will be a waste of DB performance.
EDIT
I don't know if I understand you well, but probably you need to translate property for record you already have.
You could modify then trtx
function a bit and use it this way:
{{ trtx($page, 'title') }} {{ trtx($page, 'title', 'fr') }}
(in this case you don't need to use Translate
at all)
But if I use Eloquent
(you haven't mentioned about it), you could do it also in a bit cleaner way. For your Page
model you could add accessors for title
and text
properties (you must not have title
or text
columns in your table in database):
public function getTitleAtrtribute()
{
return $this->{'title_'.\App::getLocale()};
}
public function getTextAtrtribute()
{
return $this->{'text_'.\App::getLocale()};
}
and now in your Blade
template you could use just:
<h1>{{ $page->title }}</h1>
{!! $page->text !!}