abbood
abbood

Reputation: 23558

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?

Upvotes: 11

Views: 11123

Answers (2)

afarazit
afarazit

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

3472948
3472948

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

Related Questions