Next up in the series on useful Laravel model traits is the UserTimezoneAware
Trait.
This trait is useful when you have dates on models that you need to display in the user’s timezone.
<pre class="lang:php decode:true">// app\Traits\UserTimezoneAware.php namespace App\Traits; trait UserTimezoneAware { /** * The attribute name containing the timezone (defaults to "timezone"). * * @var string */ public $timezoneAttribute = 'timezone'; /** * Return the passed date in the user's timezone (or default to the app timezone) * * @return string */ public function getDateToUserTimezone($date, $timezone = null) { if ($timezone == null) { if (Auth::check()) { $timezone = Auth::user()->timezone; } else { $timezone = Config::get('app.timezone'); } } $datetime = new DateTime($date); $datetime->setTimezone(new datetimezone($timezone)); return $datetime->format('c'); } } </pre>
It’s a simple trait you can drop onto one of your eloquent models to add timezone support like so:
<pre class="lang:php decode:true">// app\Models\User.php namespace App\Models; use App\Traits\UserTimezoneAware class User { use UserTimezoneAware; public function getLastLoginAttribute() { return $this->getDateToUserTimezone($this->attributes['last_login']); } } </pre>
Now when you access the $user->lastLogin
attribute anywhere in your app, you’ll get the date in the user’s timezone.
The UserTimezoneAware trait expects the model to have a timezone
attribute. If your column/attribute is named something other than timezone
simply override the $timezoneAttribute
property on the UserTimezoneAware
trait.
<pre class="lang:php decode:true">namespace App\Models; use App\Traits\UserTimezoneAware class User { use UserTimezoneAware; public $timezoneAttribute= 'time_zone'; }</pre>
Enjoy!