Ivanka Todorova Ivanka Todorova - 1 month ago 4
PHP Question

Model event's are not firing

I have the following code in my Post model. The

created
event is fired, but the
updated
is not.

I'm updating the model like this:

Post::where('key','=','some_key_goes_here')->first()->fill(['status' => 'approved'])->save();


And my model looks like this:

public function Post extends \Eloquent {
public static function boot()
{
parent::boot();

Post::created(function ($model) {
Queue::push('\MyApp\Jobs\Notifications\sendNotification', [
'id' => $model->user_id,
'key' => $model->key,
'status' => $model->status
]);
});

Post::updated(function ($model) {
//if the status has changed
$statusChanged = false;
foreach ($model->getDirty() as $attribute => $value) {
if ($attribute == 'status' && $model->getOriginal($attribute) != $value) {
$statusChanged = true;
}
}

if ($statusChanged) {
Notification::add($model->key, $model->status);
}
});
}
}

Answer

Little shorter version of the updated + getOriginal second param as a possible fix.

Post::updated(function ($model) {
    //if the status has changed
    foreach ($model->getDirty() as $attribute => $value) {
        if ($attribute == 'status' && $model->getOriginal($attribute, $value) != $value) {
            Notification::add($model->key, $model->status);
            break;
        }
    }
});
Comments