Laravel 如何在保存前后获取对象?
Laravel how to get object after and before saving this?
我正在使用 Laravel 4.2
我的模型有这样的功能:
ServiceLog::saved(function($servicelog) {
if($servicelog->date_created != $old_date_created) {
//do something here
}
});
我想比较保存$servicelog
前后字段date_created
的值
如何获得 $old_date_created?
根据 documentation,您有 getDirty()
和 isDirty()
方法。 isDirty
检查给定的属性是否已更改,并且 getDirty
return 是否已更改的属性。您还有 getOriginal()
方法,它将 return 给定属性的先前值(更改前)。
你能做的是:
ServiceLog::saving(function($model)
{
// Check if property has changed
if ($model->isDirty('date_created')) {
// Get the original value before the change
$oldDate = $model->getOriginal('date_created');
// Get current value for date_changed
$newDate = $model->date_created;
echo "The date_created changed from $oldDate to $newDate";
}
return true; //if false the model won't save!
});
我正在使用 Laravel 4.2
我的模型有这样的功能:
ServiceLog::saved(function($servicelog) {
if($servicelog->date_created != $old_date_created) {
//do something here
}
});
我想比较保存$servicelog
前后字段date_created
的值
如何获得 $old_date_created?
根据 documentation,您有 getDirty()
和 isDirty()
方法。 isDirty
检查给定的属性是否已更改,并且 getDirty
return 是否已更改的属性。您还有 getOriginal()
方法,它将 return 给定属性的先前值(更改前)。
你能做的是:
ServiceLog::saving(function($model)
{
// Check if property has changed
if ($model->isDirty('date_created')) {
// Get the original value before the change
$oldDate = $model->getOriginal('date_created');
// Get current value for date_changed
$newDate = $model->date_created;
echo "The date_created changed from $oldDate to $newDate";
}
return true; //if false the model won't save!
});