Model example for multilanguage

Model

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:

    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:

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:

  1. https://docs.laravelvoyager.com/core-concepts/multilanguage