Last active
August 29, 2015 14:20
-
-
Save andrewshell/76442d5ee5e1ed557227 to your computer and use it in GitHub Desktop.
Laravel UTC Model
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php namespace App\Database; | |
use Config; | |
use DateTime; | |
use DateTimeZone; | |
use Illuminate\Database\Eloquent\Model; | |
/** | |
* Always store DateTime in database as UTC | |
*/ | |
abstract class UtcModel extends Model | |
{ | |
public function getTimezone() | |
{ | |
return Config::get('app.timezone', 'UTC'); | |
} | |
/** | |
* Convert a DateTime to a storable string. | |
* | |
* @param \DateTime|int $value | |
* @return string | |
*/ | |
public function fromDateTime($value) | |
{ | |
if ($value instanceof DateTime) { | |
$value = clone $value; | |
$value->setTimezone(new DateTimeZone('UTC')); | |
} | |
return parent::fromDateTime($value); | |
} | |
/** | |
* Return a timestamp as DateTime object. | |
* | |
* @param mixed $value | |
* @return \Carbon\Carbon | |
*/ | |
protected function asDateTime($value) | |
{ | |
$default = date_default_timezone_get(); | |
date_default_timezone_set('UTC'); | |
$result = parent::asDateTime($value); | |
$result->setTimezone(new DateTimeZone($this->getTimezone())); | |
date_default_timezone_set($default); | |
return $result; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you extend this class instead of Illuminate\Database\Eloquent\Model it will automatically convert DateTime (or Carbon/Carbon) objects to UTC before saving and convert from UTC to the configured app.timezone when fetching DateTime fields from the database.
You can also overwrite the getTimezone function to choose a different timezone from app.timezone for instance based on the current users timezone or from another field in the model.