Laravel set timezone based on user preference

23 Jun, 2020

If you wonder how to set timzeone on Laravel based on user's preference, this post may be helpful for you. In this post, I will show you how to change the application timezone based on what user-defined.

I will add a column called timezone on user's table to store the logged in user's timezone.

Imagine that, we have two users those have settled following timezone.

  • User A - Timezone (Asia/Dhaka)
  • User B - Timezone (Asia/Kuala_Lumpur)

Now, I will create a new middleware called TimeZone.

php artisan make:middleware TimeZone

Now, define timezone middleware as follows-

<?php

namespace App\Http\Middleware;

use Closure;

class TimeZone
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        date_default_timezone_set(auth()->user()->timezone);

        return $next($request);
    }
}

Now, let's register the middleware in the web middlewareGroup in App\Http\Kernel.php file.

protected $middlewareGroups = [
        'web' => [
            \App\Http\Middleware\EncryptCookies::class,
            \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
            \Illuminate\Session\Middleware\StartSession::class,
            // \Illuminate\Session\Middleware\AuthenticateSession::class,
            \Illuminate\View\Middleware\ShareErrorsFromSession::class,
            \App\Http\Middleware\VerifyCsrfToken::class,
            \Illuminate\Routing\Middleware\SubstituteBindings::class,
            \App\Http\Middleware\TimeZone::class,
        ],

Now, if you store user's timezone, the entire application will follow whatever timezone user defines.

Note: Please take a note that, this solution is only for logged-in user. If you need to apply on the guest as well, you need to adjust your middleware based on your preference.

Thank you. :)

Hello. I’m Thouhedul Islam. Some people also know me as Suchi.

I am a Full-stack Developer. I love to play with PHP specially Laravel, JavaScript, MySql and latest web technology. Currently I am working for CartX as my day time job.

At night I love to solve problem for community. I am quite active at Laracasts