Reputation: 81
I have in my table a timestamps with created_at and updated_at
$table->timestamps();
But I want to add another column that calculates the difference between created_at and updated_at in days
Should I do that in SQL or in my controller?
Upvotes: 0
Views: 10435
Reputation: 2945
Use Carbon
for count date difference in days.
$to = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $created_at);
$from = \Carbon\Carbon::createFromFormat('Y-m-d H:i:s', $updated_at);
$diff_in_days = $to->diffInDays($from);
Upvotes: 0
Reputation: 341
To have it auto save this value on every update to that model, then you can put this in the model.
public static function boot()
{
parent::boot();
static::updating(function($model) {
$diffInDays = $model->updated_at->diffInDays($model->created_at);
$model->timestamp_difference = $diffInDays;
});
}
timestamp_difference
is the name of the DB column that I used, this can be whatever you want it to be.
Upvotes: 0
Reputation: 3553
You can do that from within your Eloquent model.
Let's assume your model has the name User
.
You can create a computed field by defining an Accessor.
class User extends Model
{
$dates = [
'updated_at',
'created_at'
];
$appends = ['diffInDays'];
public function getDiffInDaysAttribute()
{
if (!empty($this->created_at) && !empty($this->updated_at)) {
return $this->updated_at->diffInDays($this->created_at);
}
}
}
By adding created_at
and updated_at
to the $dates
array, Laravel automatically casts your date values to Carbon.
Now, if you do something like $user->created_at
, you don't get the string, but a Carbon instance of that date. This allows you to make some nice date calculations, like the one above.
By adding an Accessor with the getDiffInDaysAttribute
function, you can call the days difference via $user->diffInDays
like a normal attribute, although it is not on the model.
But if you would now do something like $user->toArray()
, the diffInDays
attribute will not be available.
To always add the difference in days when you retrieve User data, you can add the field to the $appends
array.
That way, the field will always be returned when you retrieve User data via Eloquent.
Upvotes: 1