Eloquent stores Array-casted value in other order

Viewed 48

In my code I have an Eloquent model which has one JSON-column steps, which is casted as array:

protected $casts = [
    'steps'  => 'array',
];

But if I know update the column with an array like this:

    $model->update([
        'steps' => [
            'connect' => 'A', 'clone' => 'A'
        ]
    ]);

Anything internally changes the order of json-array which is stored to the database, which looks like this now:

enter image description here

Any ideas how to prevent Eloquent from changing the order of the array items while storing them?

Little Update: The array is always sorted alphabetically by the keys before stored.

1 Answers

Your data structure should be like this:

[
    {"connect": "A"},
    {"clone": "A"}
]

because this is steps array and any step should be considered as a separate entity.

$model->update([
    'steps' => [
        ['connect' => 'A'],
        ['clone' => 'A']
    ]
]);

In this way not only you have right structure to store in DB but also you can store it in the order you want.

Related