Skip to content

OriginalIsEquivalent failed for array types #57384

@hussonkevin

Description

@hussonkevin

Laravel Version

12.20

PHP Version

8.4

Database Driver & Version

MySQL 8.0

Description

Hello,
There's a problem with the "originalIsEquivalent" method of the "HasAttributes" trait for array types (json, array, etc.).
If I overwrite my model with the same value as the one already defined in the database, the method returns false if the order isn't the same.
This makes sense because the strict php comparison "===" also checks the order of the keys...
The problem is that when saving, the keys are sometimes/often reordered! So the "getDirty" method returns the key.

Steps To Reproduce

In the model, use the array cast and then the step to reproduce:

$data =  ['test' => 'test', 'value1'];
$model = new Model;
$model->data = $data;
$model->save();

$model = Model::find(1); // or $model->refresh();
$model->data = $data;
$model->getDirty(); // -> returns the key data

The fix could be the following:

} elseif ($this->hasCast($key, static::$primitiveCastTypes)) {
    $castedAttribute = $this->castAttribute($key, $attribute);
    $castedOriginal = $this->castAttribute($key, $original);
    if (is_array($castedAttribute) && is_array($castedOriginal)) {
        ksort($castedAttribute);
        ksort($castedOriginal);
    }
    return $castedAttribute === $castedOriginal;
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions