Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

PeterF's avatar

Eloquent, Timezones and transactions.

I have a transactional application that spans multiple time zones for both the transactions, and the people that view the transactions. Timezones have always been a massive pain in the rear..... but what I ended up with was,

  1. store everything in the DB in UTC
  2. store the users current timezone in a Session variable
  3. plug into the eloquent loading lifecycle and when a record is read from the DB, convert it with the TZ stored in the users session for display purposes.

It was all going very well, until I had to do my first Job on a queue..... then the TZ was not available as there was no session......

So what does everyone else do for this kind of thing?

0 likes
3 replies
fylzero's avatar

@peterf Can you pass the timezone to the job when it is dispatched by adding it to the __construct?

PeterF's avatar

@fylzero Yeah, I may need to. Because my transactions are actually part of a multi-tenancy based on the Auth::id(), i got bitten by that, and added those details to the JOb constructor to make it work. The problem is the TZ values are being set as part of the eloquent life cycle listeners set in the model like this

/**
     * The event map for the model.
     *
     * @var array
     */
    protected $dispatchesEvents = [
        'saving' => ExecutionSaving::class,
        'retrieved' => ExecutionRetrieved::class,
    ];

and then in those event listener classes, it pulls the TZ from the Session to do the timestamp conversion on the way in and out of the DB. It seemed so neat and beautiful when I did it. So if I pass it into the Job constructor, it doesnt help, because it fails down in the low levels........ I am wondering as I type this, if maybe storing the users TZ in the Session object is maybe the bit that it wrong. Perhaps it needs to go in the Cache object so it can be grabbed from the inside of the eloquent event processing and then it will work if its attached to a user or not.....

Snapey's avatar

if what you are doing relates to a user, then use their preferred timezone directly from the authenticated user

if the activity is for a user but they are not present then you need to pass the timezone required into the job / mail etc

As you have noted, session is only of use for http requests where you can easily access Auth::user()->timezone

caching wont work as cache is global across all users, and you can't key it by user since in some situations you don't know the user

Please or to participate in this conversation.