Model
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
namespace App; use Illuminate\Database\Eloquent\Model; use TCG\Voyager\Traits\Translatable; use App\Traits\TranslateModelAttributes; class Product extends Model { use Translatable; // Provide a function to translate all attributes use TranslateModelAttributes; protected $translatable = ['text1', 'text2', 'price']; } |
Controller:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
private function trans_model($data){ $locale = App()->getLocale(); if(is_array($data) == true || is_collection($data) == true){ foreach ($data as $key => $item) { $item->langs($locale, $this->fallback_locale); } }else{ $data = $data->langs($locale, $this->fallback_locale); } return $data; } public function team(Request $req){ $data = $this->view_data(); $admins = Member::withTranslations() ->where('category_id', 4) ->orderBy('sort_order', 'asc') ->get(); $admins = $this->trans_model($admins); $data['admins'] = $admins; //dd(App()->getLocale()); $data['page_title'] = '臺灣館策展工作團隊'; return view('team', $data); } |
Trait to translate model:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
namespace App\Traits; // To set $locale value of a model and translate all translatable attributes trait TranslateModelAttributes { protected $locale = 'zhtw'; protected $fallback_locale = 'en'; public function langs($locale, $fallback_locale='en'){ $this->locale = $locale; $this->fallback_locale = $fallback_locale; foreach ($this->translatable as $key => $column) { $value = $this->getTranslatedAttribute($column, $locale); if($value == false){ $value = $this->getTranslatedAttribute($column, $fallback_locale); } $this->{$column} = $value; } return $this; } } |
Reference: