4

When you have an array field and save it in the DB it does a nifty json_encode to the array but without the JSON_UNESCAPED_UNICODE option. The data end up like so :

{"en":"\u039d\u03ad\u03b1"}

which is pretty much useless. The solution of course is to json_encode with the JSON_UNESCAPED_UNICODE flag. Is it possible to tell Laravel to add this option before saving the model?

I am trying to avoid using the setNameAttribute mutator as this would be kind of a pain to do it every time i have this type of fields

mbouclas
  • 634
  • 1
  • 12
  • 30

2 Answers2

20

Just override the asJson() method.

class Cat extends Model
{

    // ...

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

}

If you don't want to repeat the method for all your models, just extract the method to an abstract class:

abstract class UnicodeModel extends Model 
{
    protected function asJson($value)
    {
        return json_encode($value, JSON_UNESCAPED_UNICODE);
    }
}

Now you inherit from UnicodeModel instead of Model:

class Cat extends UnicodeModel 
{
    // ...
}

In case you need a finer casting control you can override the setAttribute method, e.g.:

class Cat extends Model
{

    // ...

    public function setAttribute($key, $value)
    {

        // take special care for the attributes foo, bar and baz
        if (in_array($key, ['foo', 'bar', 'baz'])) {
            $this->attributes[$key] = json_encode($value, JSON_UNESCAPED_UNICODE);

            return $this;
        }

        // apply default for everything else
        return parent::setAttribute($key, $value);
    }
}
maxwilms
  • 1,964
  • 20
  • 23
3

Better for Laravel's Model:

$yourModel->toJson(JSON_UNESCAPED_UNICODE)
FelixSFD
  • 6,052
  • 10
  • 43
  • 117
Tomer Ofer
  • 378
  • 3
  • 15