In Laravel 4.2, when a record is created in the database, using eloquent, we can have created_at and updated_at timestamps created.
I would like to add a third column to the table I am working with that is called expires and I would like to set the value of that column to created_at + 72 hours
Is there a "Laravel" way to do this? To access created_at value? Or should I approach this differently?
Laravel's created_at is a an instance of Carbon. Using an accessor, we can populate $model->expires like so:
public function getExpiresAttribute() {
$expires = clone $this->created_at;
$expires->addHours(72);
return $expires;
}
If you want to be able to query against the value (rather than just calculating for display), though, you'd need to store it in the database. To have it automatically populate, you can tell Laravel it's a date column and use an observer:
public function getDates(){
return ['created_at', 'updated_at', 'expires'];
}
public static function boot() {
parent::boot();
self::creating(function($model) {
$model->expires = clone $model->created_at;
$model->expires->addHours(72);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With