0

I'm writing my application with 'UTC' as the time zone. I have a timezone column for each user. I am going to use this value in the presentation layer. Date/time outputs and inputs will be using it.

I will also be presenting dates and times in the view layer when there's no current user. I want the fallback time zone to be the application one. I want to avoid putting logic like this every time:

$now = new Carbon();
if (!Auth::guest()) {
    $now->setTimezone(Auth::user()->timezone);
}

All this finally leads me to my question. Where/how is a good place to set the view layer time zone?

I'm providing my own answer, but I'm looking for better solutions, criticisms, etc.

Sonny
  • 8,204
  • 7
  • 63
  • 134
  • Middleware that sets the `app.timezone` config at runtime, perhaps? – ceejayoz Aug 29 '17 at 14:37
  • @ceejayoz - I don't want to change the application time zone, but I am intrigued about you pointing to using middleware. As a Laravel n00b, I'm not quite sure how middleware would be used. Would you please elaborate? – Sonny Aug 29 '17 at 14:39
  • Doing `config('app.timezone', 'Foo/Bar')` will only affect that one request - it won't affect the rest of the application or other pageviews. As for middleware, https://laravel.com/docs/5.4/middleware – ceejayoz Aug 29 '17 at 14:43
  • @ceejayoz - I don't want to change it for the request either. I want the config value to remain always. Thanks for the link! – Sonny Aug 29 '17 at 14:45

1 Answers1

0

Set the session value during authentication (login)...

Auth::login($user);
session(['timezone', $user->timezone]);

Use it in the view layer...

{{ \Carbon\Carbon::now()->setTimezone(session('timezone'))->format('h:i A T') }}
Sonny
  • 8,204
  • 7
  • 63
  • 134