Reputation: 23558
following this answer, I do model save callbacks (similar to rails) in Laravel like so:
class LessonPlan extends Eloquent {
public function save(array $options = array())
{
// before save code
parent::save();
// after save code
}
}
However, I call save() on Page
when i'm saving a new page or updating an existing one. How do I know which is which in this operation?
I tried something like
public function save(array $options = array())
{
// before save code
$oldLesson = clone $this;
parent::save();
..
if ($this->isLessonStatusChanged($oldLesson)) {
..
}
}
private function isLessonStatusChanged($oldLesson) {
return $this->status != $oldLesson->status;
}
but that's no good.. since $oldLesson will already have the new values of $lesson
what I ended up doing was simply regexing the url to see if it's an update request.. but I'm already having trouble sleeping at night (my answer doesn't really tell me if any values have actually changed.. b/c one can submit an update form without actually changing anything).. is there a cleaner way of doing this?
Upvotes: 11
Views: 11123
Reputation: 4984
You can use the isDirty()
method which returns a bool
and getDirty()
which returns an array
with the changed values.
public function save(array $options = array())
{
$changed = $this->isDirty() ? $this->getDirty() : false;
// before save code
parent::save();
// Do stuff here
if($changed)
{
foreach($changed as $attr)
{
// My logic
}
}
}
Upvotes: 14
Reputation: 821
Have you tried Model::getDirty()
? I haven't tried it myself but it returns the attributes that have changed since the last sync. See the API docs.
Upvotes: 0