Skip to content

Instantly share code, notes, and snippets.

@frikishaan
Last active May 10, 2024 11:28
Show Gist options
  • Save frikishaan/38ea39f22190e98339ff7bf4da9906ee to your computer and use it in GitHub Desktop.
Save frikishaan/38ea39f22190e98339ff7bf4da9906ee to your computer and use it in GitHub Desktop.
Laravel Custom Cast to convert datetime fields to user's timezone
<?php
/*
* This custom cast will help convert a datetime field in database to local timezone of the user
* This also convert any input datetime string from user's timezone to the app's default timezone
*/
namespace App\Casts;
use Carbon\Carbon;
use Illuminate\Contracts\Database\Eloquent\CastsAttributes;
use Illuminate\Database\Eloquent\Model;
class DateTimeWithTz implements CastsAttributes
{
/**
* Cast the given value.
*
* @param array<string, mixed> $attributes
*/
public function get(Model $model, string $key, mixed $value, array $attributes): mixed
{
return Carbon::parse($value, config('app.timezone'))->setTimezone(auth()->user()->timezone);
}
/**
* Prepare the given value for storage.
*
* @param array<string, mixed> $attributes
*/
public function set(Model $model, string $key, mixed $value, array $attributes): mixed
{
return Carbon::parse($value, auth()->user()->timezone)->setTimezone(config('app.timezone'));
}
}
/* Example use
public function casts()
{
return [
'end_date' => DateTimeWithTz::class,
];
}
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment