Created
February 18, 2023 07:16
-
-
Save mohamedsabil83/5d660228b236437c3c78b21959f6a2c9 to your computer and use it in GitHub Desktop.
A trait for spatie/laravel-translatable to support unescaped Unicode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
namespace App\Traits; | |
use Illuminate\Support\Str; | |
use Spatie\Translatable\Events\TranslationHasBeenSetEvent; | |
use Spatie\Translatable\HasTranslations as baseHasTranslations; | |
trait HasTranslations | |
{ | |
use baseHasTranslations; | |
public function setTranslation(string $key, string $locale, $value): self | |
{ | |
$this->guardAgainstNonTranslatableAttribute($key); | |
$translations = $this->getTranslations($key); | |
$oldValue = $translations[$locale] ?? ''; | |
if ($this->hasSetMutator($key)) { | |
$method = 'set'.Str::studly($key).'Attribute'; | |
$this->{$method}($value, $locale); | |
$value = $this->attributes[$key]; | |
} | |
$translations[$locale] = $value; | |
$this->attributes[$key] = json_encode($translations, JSON_UNESCAPED_UNICODE); | |
event(new TranslationHasBeenSetEvent($this, $key, $locale, $oldValue, $value)); | |
return $this; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
After more reviews and tests, the simplest way is the following:
I'll keep the above HasTranslations overridden too.