Last active
June 30, 2020 15:04
-
-
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
This file contains 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 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