Skip to content

Instantly share code, notes, and snippets.

@paulund
Last active June 30, 2020 15:04
Show Gist options
  • Save paulund/b2fe4b7cfe71381b1521c90db46d49dc to your computer and use it in GitHub Desktop.
Save paulund/b2fe4b7cfe71381b1521c90db46d49dc to your computer and use it in GitHub Desktop.
Laravel UTC DateTime custom cast see tutorials on custom casts https://paulund.co.uk/laravel-custom-casts
<?php
namespace CustomCast;
use Carbon\Carbon;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
class UtcDateTime implements CastsAttributes
{
/**
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
*
* @return Carbon|mixed
*/
public function get($model, string $key, $value, array $attributes)
{
if (is_string($value)) {
return Carbon::parse($value)->setTimezone(config('app.timezone'));
}
return $value->copy()->setTimezone(config('app.timezone'));
}
/**
* @param \Illuminate\Database\Eloquent\Model $model
* @param string $key
* @param mixed $value
* @param array $attributes
*
* @return array|Carbon|string
*/
public function set($model, string $key, $value, array $attributes)
{
if (is_string($value)) {
return Carbon::parse($value)->setTimezone('UTC');
}
return $value->copy()->setTimezone('UTC');
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment