Laravel set timezone based on user preference

Laravel set timezone based on user preference

Posted on:June 23, 2020 at 10:00 AM

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. :)