Last active
September 18, 2018 22:31
-
-
Save paslandau/b2e17820f7458943967c to your computer and use it in GitHub Desktop.
Dirty fix for Model::isDirty() in Laravel to honor the $casts attribute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Determine if the model or given attribute(s) have been modified. | |
* | |
* @param Model $m | |
* @param array|string|null $attributes | |
* @return bool | |
*/ | |
function _is_dirty(Model $m, $attributes = null){ | |
$castAttribute = new ReflectionMethod(Model::class,"castAttribute"); | |
$castAttribute->setAccessible(true); | |
$props = [ | |
"original", | |
"attributes" | |
]; | |
//cast every value in original and attributes | |
foreach($props as $prop){ | |
$p = new ReflectionProperty(Model::class,$prop); | |
$p->setAccessible(true); | |
$o = $p->getValue($m); | |
foreach($o as $key => $value){ | |
if($m->hasCast($key)){ | |
$o[$key] = $castAttribute->invoke($m,$key,$value); | |
} | |
} | |
$p->setValue($m, $o); | |
} | |
return $m->isDirty($attributes); | |
} | |
$m = new Model(); | |
//old | |
// $m->isDirty(); | |
//new | |
_is_dirty($m); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment