Skip to content

Instantly share code, notes, and snippets.

@paslandau
Last active Sep 18, 2018
Embed
What would you like to do?
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