Given the amount of data (unless your app is very text heavy) It can be easier / better / quicker to get all the text for that language on load and then a simple getter to that array of information.
E.g. on load (base controller or whatever) get the entire language and store in an array/object.
Then get the text required by ID to that array/object This can be further optimised by caching this store - as a local store object. (e.g. not loaded on subsequent visits by the user)
Means one longer init query, but post that, no impact on the system. Given that a page could use 50 text translations it can be very beneficial.
This is a problem, for example opencart suffers from on something very similar. Front loading it all makes even a very light text page more efficient overall.
Again depends on your app - but worth considering.
Thank MatyHaty for your answer. Unfortunately the app will be very text heavy. That is what we 'sell'. For now I created an extra method in my model:
public function translate($fieldName) {
return $this->newCollection((array)$this->hasMany('Translation', 'translatable_id', $fieldName)
->with('language')->get())->inLanguage();
}
The Collection method does the following:
public function inLanguage()
{
$models = $this;
$returnArray = [];
foreach($models as $key => $model) {
foreach($model as $languages) {
$returnArray['to' . ucfirst(strtolower($languages->language->english_name))] = $languages->translation;
$returnArray[strtolower($languages->language->abbreviation)] = $languages->translation;
}
}
return (object) $returnArray;
}
So in my controller I can do the following:
ShopCategory::find(1)->translate('description')->en
or
ShopCategory::find(1)->translate('description')->toEnglish
This took the amount of queries back to three.
description
)Downside of this method is that i have to re-create this method over and over for every model I want to make translatable. And when I need to collect multiple field (eg: product name, product short description, product description, et cetera) I drastically increase the amount of SQL-queries. Probably need to load the language meta data on app start up (as you suggest), but I am still having the problem of not being able to eager load a whole models translations.
Maybe you have an idea for this?
Thanks in advance!
Here is an different approach on translating Eloquent objects: https://github.com/vinkla/translator
Hello @deargonaut,
I 've created a package igaster/laravel-translate-eloquent that adds translation to any Eloquent Model. It requires only one additional table in your DB where all the translations will be stored...
Hope it is usefull... Cheers!
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community