Laravel 4.2 - Adding Time to Timestamp

In Laravel 4.2, when a record is created in the database using eloquence, we can create created_at and updated_at timestamps.

I would like to add a third column to the table I am working with which is called expires

and I would like to set the value of that column tocreated_at + 72 hours

Is there a "Laravel" way to do this? To access the created_at value? Or should I approach this differently?

+3


source to share


1 answer


Laravel created_at

is a Carbon instance. Using an accessor, we can fill in $model->expires

like this:

public function getExpiresAttribute() {
  $expires = clone $this->created_at;
  $expires->addHours(72);
  return $expires;
}

      



If you want to be able to query the value (rather than just compute to display), however, you will need to store it in the database. To automatically fill it in, you can tell Laravel about the 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);
  }
}

      

+5


source







All Articles