Reputation: 3460
I'm creating a Laravel project but I have an issue.
I'm trying to save the difference between 2 timestamps to the database before I save the model:
My table:
$table->increments('id');
$table->time('from');
$table->time('to');
$table->time('diff');
So.. before inserting, calculate the difference between these two times and insert this on the same time.
Is this possible and can anyone help me?
Thankyou,
Upvotes: 0
Views: 658
Reputation: 2254
You can hook into saving() or updating() or creating()
so in your model add one of the above depending on which one you want to hook (I think saving() if I understand you correctly) and implement sth like the following:
public static function boot()
{
parent::boot();
static::saving(
function ($table) {
$table->diff = strtotime($table->to) - strtotime($table->from);
}
);
}
Upvotes: 2
Reputation: 31225
To calculate the different between to and from in seconds:
$row = TableModel::find(123);
$diff = strtotime($row->to) - strtotime($row->from);
$row->diff = $diff;
$row->save();
Upvotes: 0