Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to know if laravel model values changed on save callback

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?

like image 330
abbood Avatar asked Apr 16 '14 11:04

abbood


1 Answers

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
        }
    }

}
like image 134
afarazit Avatar answered Oct 17 '22 07:10

afarazit