Skip to content

Instantly share code, notes, and snippets.

@paslandau
Last active September 18, 2018 22:31
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save paslandau/b2e17820f7458943967c to your computer and use it in GitHub Desktop.
Save paslandau/b2e17820f7458943967c to your computer and use it in GitHub Desktop.
Dirty fix for Model::isDirty() in Laravel to honor the $casts attribute
<?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