Created
September 24, 2020 05:58
-
-
Save fhferreira/bed8b79b42f657caf402041b0aa1a535 to your computer and use it in GitHub Desktop.
Localized Date Time Casting In Laravel- https://laravel.com/docs/7.x/eloquent-mutators#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 App\Casts; | |
use Carbon\Carbon; | |
use Illuminate\Contracts\Database\Eloquent\CastsAttributes; | |
class LocalizedDateTime implements CastsAttributes | |
{ | |
/** | |
* Cast the given value. | |
* | |
* @param \Illuminate\Database\Eloquent\Model $model | |
* @param string $key | |
* @param mixed $value | |
* @param array $attributes | |
* @return array | |
*/ | |
public function get($model, $key, $value, $attributes) | |
{ | |
if (! $value) { | |
return null; | |
} | |
return (new Carbon($value))->tz(auth()->user()->timezone ?? $model->timezone ?? 'UTC'); | |
} | |
/** | |
* Prepare the given value for storage. | |
* | |
* @param \Illuminate\Database\Eloquent\Model $model | |
* @param string $key | |
* @param array $value | |
* @param array $attributes | |
* @return string | |
*/ | |
public function set($model, $key, $value, $attributes) | |
{ | |
return $value; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment