Skip to content

Instantly share code, notes, and snippets.

@mohamedsabil83
Created February 18, 2023 07:16
Show Gist options
  • Save mohamedsabil83/5d660228b236437c3c78b21959f6a2c9 to your computer and use it in GitHub Desktop.
Save mohamedsabil83/5d660228b236437c3c78b21959f6a2c9 to your computer and use it in GitHub Desktop.
A trait for spatie/laravel-translatable to support unescaped Unicode
<?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;
}
}
@mohamedsabil83
Copy link
Author

After more reviews and tests, the simplest way is the following:

<?php

namespace App\Traits;

trait SupportUnescapedUnicode
{
    protected function asJson($value)
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}

I'll keep the above HasTranslations overridden too.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment