Skip to content

Instantly share code, notes, and snippets.

@igorblumberg
Created April 4, 2016 13:01
Show Gist options
  • Save igorblumberg/a03fbb17984379b36d391474a45dd673 to your computer and use it in GitHub Desktop.
Save igorblumberg/a03fbb17984379b36d391474a45dd673 to your computer and use it in GitHub Desktop.
<?php
namespace App\Traits\Models;
use Illuminate\Database\Eloquent\Model;
use App\Models\Translation;
use \LaravelLocalization;
use DB;
trait TranslatableTrait
{
public function __get($key)
{
if(isset($this->translatable) && in_array($key, $this->translatable))
{
//translate and return
return $this->getTranslation($key);
}
else
{
//don't translate, call parent
return parent::__get($key);
}
}
//can't use __set since when the model is created there isn't any ID yet, so we first need to save the model and then the translations
public function save(array $options = [])
{
$result = parent::save($options);
if($result)
{
if(isset($this->translatable))
{
$table = $this->getTable();
$instance = DB::table($table)->where("id",$this->id)->first();
foreach($this->translatable as $key)
{
$this->setTranslation($key,$instance->{$key});
}
}
return true;
}
else
{
return false;
}
}
public function trans($key,$locale)
{
return $this->getTranslation($key,$locale);
}
public function getTranslation( $key, $locale = NULL )
{
if(!$locale)
{
$locale = LaravelLocalization::getCurrentLocale();
}
//model class, model id, locale code
$translation = Translation::where("model_class",get_class($this))->where("model_id",$this->id)->where("key",$key)->where("locale",$locale)->first();
if(!$translation)
{
return "";
// return parent::__get($key);
}
else
{
return $translation->value;
}
}
public function setTranslation($key,$value,$locale = NULL)
{
if(!$locale)
{
$locale = LaravelLocalization::getCurrentLocale();
}
$translation = Translation::where("model_class",get_class($this))->where("model_id",$this->id)->where("key",$key)->where("locale",$locale)->first();
if(!$translation)
{
$translation = new Translation;
$translation->model_class = get_class($this);
$translation->model_id = $this->id;
$translation->key = $key;
$translation->locale = $locale;
$translation->value = $value;
}
else
{
$translation->value = $value;
}
return $translation->save();
}
public function toJson($locale = NULL)
{
if(!$locale)
{
$locale = LaravelLocalization::getCurrentLocale();
}
$array = $this->toArray();
if(isset($this->translatable))
{
foreach($this->translatable as $value)
{
$array[$value] = $this->getTranslation($value,$locale);
}
}
return json_encode($array);
}
public function delete()
{
Translation::where("model_class",get_class($this))->where("model_id",$this->id)->delete();
return parent::delete();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment