Skip to content

Instantly share code, notes, and snippets.

@paulund
Last active Jun 30, 2020
Embed
What would you like to do?
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