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?
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
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With