Skip to content

Instantly share code, notes, and snippets.

@andrewshell
Last active August 29, 2015 14:20
Embed
What would you like to do?
Laravel UTC Model
<?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;
}
}
@andrewshell
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment