70 lines
1.8 KiB
PHP
70 lines
1.8 KiB
PHP
<?php
|
|
|
|
namespace App;
|
|
|
|
use App\Repositories\ModelTranslationRepository;
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use App\Observers\TranslatableModelOberserver;
|
|
|
|
class TranslatableModel extends Model
|
|
{
|
|
protected $translatableAttributes = [];
|
|
|
|
protected static function boot()
|
|
{
|
|
parent::boot();
|
|
|
|
static::observe(TranslatableModelOberserver::class);
|
|
}
|
|
|
|
public function __get($attribute)
|
|
{
|
|
return $this->trans($attribute, app()->getLocale());
|
|
}
|
|
|
|
public function defaultValue($attribute)
|
|
{
|
|
return parent::__get($attribute);
|
|
}
|
|
|
|
public function trans($attribute, $locale = null)
|
|
{
|
|
if(in_array($attribute, $this->translatableAttributes)) {
|
|
$currentLocale = $locale ? $locale : app()->getLocale();
|
|
|
|
$transRepo = app(ModelTranslationRepository::class);
|
|
|
|
$transRepo->setTranslatedModel($this);
|
|
|
|
$value = $transRepo->getModelTranslation($this->id, $attribute, $currentLocale);
|
|
|
|
if($value === null) {
|
|
$value = $this->defaultValue($attribute);
|
|
}
|
|
|
|
return $value;
|
|
} else {
|
|
return $this->defaultValue($attribute);
|
|
}
|
|
}
|
|
|
|
public function getTranslatableAttributes()
|
|
{
|
|
return $this->translatableAttributes;
|
|
}
|
|
|
|
public function translations()
|
|
{
|
|
return $this->morphMany(ModelTranslation::class, 'model');
|
|
}
|
|
|
|
public function scopeSearchInTranslation($query, $attribute, $keyword)
|
|
{
|
|
$keyword = '%' . implode('%', preg_split('//u', $keyword, -1, PREG_SPLIT_NO_EMPTY)) . '%';
|
|
|
|
return $query->whereHas('translations', function($query) use($attribute, $keyword) {
|
|
$query->where('attribute', $attribute)->where('content', 'LIKE', $keyword);
|
|
});
|
|
}
|
|
}
|