What's the trick here guys? I want to set this globally for each user. What's the best approach? In user table I have timezone column (default, 'America/New_York, etc.).
@mikebarwick setting the app.timezone config key inside a middleware won't help, because by the time a request will reach the middleware Laravel would have already utilized this key. You will need to use the date_default_timezone_set() function.
You can create a separate middleware or you can just utilize the Authenticate middleware with the following changes:
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
if ($this->auth->guest())
{
if ($request->ajax())
{
return response('Unauthorized.', 401);
}
else
{
return redirect()->guest('login');
}
}
date_default_timezone_set($this->auth->user()->timezone);
return $next($request);
}
Just my two cents :)
Update://
My bad, using Authenticate middleware will only set the timezone for authenticated routes. You will need a separate middleware.
@usman I think you were right in the first place... you can't set a user' time zone unless you know who they are, which probably means they will have to be authenticated.
If not authenticated, then the other possibility is to give the user a cookie when they do login and set their preferred time zone. This cookie could then be examined at each session start. A bit like Amazon knows who I am when I first hit the site but then I have to login to do anything with my account.
Question - is this the best practice though? the more I think about it. What happens if the user changes timezones? In what I'm building, a company can have many users (that can assign tasks to everyone). What happens if person A in Toronto sets a task for 3pm, but person B (who the task is assigned to) lives in California?
I am making an app where user can publish an article. If somebody in Japan publishes an article on 2017/03/25 09:00 should I set the articles published date and time to that time or should I set it to servers time?
Also if somebody in USA enters the website and is about to read the article, what date should the article say it was published?
If I say 2017/03/25 09:00 that time has not happend yet for the user in the USA and it would be in future for him, what time should I show to somebody from the other end of the world?