Adam Anderly

Husband, Father, Developer

  • About
  • Blog
  • Archives
  • Plugins
    • WooCommerce MailChimp
    • Wistia Responsive
  • Contact

Copyright © 2023
Adam Anderly · Log in

Laravel User Timezone Aware Trait

December 21, 2017 By Adam Leave a Comment

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!

Share this:

  • Twitter
  • LinkedIn
  • Email
  • Print
  • More
  • Reddit

Filed Under: Laravel, Laravel Traits, PHP Tagged With: Laravel, Laravel Traits, PHP

RSS

RSS Feed

Subscribe

Enter your email address to subscribe and receive new posts by email.

Find It Here

Top Posts

  • Cross-Cutting Concerns with MediatR Pipeline Behaviors
  • Create your own branded url-shortener in under 10 minutes using ASP.NET MVC 2
  • Laravel User Timezone Aware Trait
  • Laravel Transformable - An Eloquent Model Trait for Consumable Models

Recent Posts

  • Cross-Cutting Concerns with MediatR Pipeline Behaviors
  • Laravel User Timezone Aware Trait
  • Useful Laravel Model Traits: Gravatar
  • Laravel Transformable – An Eloquent Model Trait for Consumable Models
  • Gravity Forms + Microsoft Dynamics CRM

Categories

  • .NET (12)
  • ASP.NET Core (1)
  • ASP.NET MVC (7)
  • Dependency Injection (3)
  • Laravel (3)
  • Laravel Traits (2)
  • MediatR (1)
  • Node.js (2)
  • NuGet (5)
  • PHP (2)
  • REST (4)
  • Silverlight (5)
  • Uncategorized (3)
  • WordPress (7)
  • WordPress Plugins (7)

Tags

.NET APIs ASP.NET Core ASP.NET MVC Azure Caching cli CRM Dependency Injection dns dnsimple Dynamics Dynamics CRM Expansive Fallback Gravity Forms iPhone Laravel Laravel Traits MailChimp MediatR Microsoft Dynamics CRM MobileMe Node.js NuGet PHP Polly REST Retry Rounding Scrutor Silverlight SimpleMembership sublime-text-2 VS2010 Wistia WooCommerce WordPress WordPress Plugins
  • About
  • Blog
  • Archives
  • Plugins
    • WooCommerce MailChimp
    • Wistia Responsive
  • Contact
loading Cancel
Post was not sent - check your email addresses!
Email check failed, please try again
Sorry, your blog cannot share posts by email.