Check if an object has changed

前端 未结 5 2318
闹比i
闹比i 2021-02-19 21:31

Is there a more native way (e.x. a built-in function) with less userland code to check if an objects property values have changed instead of using one of those methods:

5条回答
  •  野的像风
    2021-02-19 22:16

    We can implement it without observer.

    For pure php, we can use $attributes & $original to check what has been modified check this explanation if needed.

    $modifiedValues = [];
    foreach($obj->attributes as $column=>$value) {
        if(!array_key_exists($column, $obj->original) || $obj->original[$column] != $value) {
            $modifiedValues[$column] = $value;
        }
    }
    // then check $modifiedValues if it contains values
    

    For Laravel user, we can use the isDirty() method. Its usage:

    $user = App\User::first();
    $user->isDirty();          //false
    $user->name = "Peter";
    $user->isDirty();          //true
    

提交回复
热议问题