0

I have a JSON field in a database which is populated using the array cast on an Eloquent model.

Before saving the field, Laravel sorts the elements by their key. Presumably this happens during serialisation.

Why does it do this? And is there a way to prevent it?

DatsunBing
  • 7,624
  • 11
  • 71
  • 141

2 Answers2

1

If you do not need to implement search by field, you can use the text type instead of the json type. Just before saving, you will need to execute json_encode, either yourself or implement a mutator.

0

I've never encountered this behavior before, but perhaps you can try using an accessor and a mutator to accomplish what you want. Let's say your database column is meta. You can use Laravel's special setAttribute and getAttribute methods in your model.

A mutator

For example, to json_encode data as it's about to be saved to your database it would be:

public function setMetaAttribute($value)
{
    $this->attributes['meta'] = json_encode($value);
}

An accessor

To json_decode data as it's being retrieved it would be:

public function getMetaAttribute($value)
{
    return json_decode($value, true);
}

The rule of thumb is take get or set and append your column name with first letters uppercased and removing any underscores, and appending Attribute to the method name. E.g. active_users column becomes getActiveUsersAttribute and so on.

Try that and see if it does any funky sorting.

Mark
  • 1,101
  • 1
  • 7
  • 17