Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 Model $cats to array utf-8 JSON_UNESCAPED_UNICODE

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

like image 875
mbouclas Avatar asked Nov 30 '22 16:11

mbouclas


2 Answers

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);
    }
}
like image 85
maxwilms Avatar answered Dec 03 '22 04:12

maxwilms


Better for Laravel's Model:

$yourModel->toJson(JSON_UNESCAPED_UNICODE)
like image 36
Tomer Ofer Avatar answered Dec 03 '22 05:12

Tomer Ofer