How to Automatically Set a Local Timezone for Users in Laravel ?

Updated 27 April 2020

Introduction

Timezone is a laravel package created by James Mills. The main task of timezone package is to set a timezone for different users for different time zones in the application, and show them their local time.

How does it work ?

It works by listening for the user login event and setting the timezone in the database. It uses Laravel GeoIP to look up the user using an IP address.

This package listens for the \Illuminate\Auth\Events\Login event and will then automatically set a timezone on your user model (stored in the database).

This package listens for the \Illuminate\Auth\Events\Login event and will then automatically set a timezone on your user model (stored in the database).

How to use it ?

You can simply show dates to your user by using the command below:

Or directly use this blade directive:

How to install it to your laravel application ?

Step 1: Install the package by the composer

Step 2: Publish database Migrations

Step 3: Run the database migrations. This will add a timezone column to your users table.

Example

Default will use the format jS F Y g:i:a and will not show the timezone

If you wish you can set a custom format and also include a nice version of the timezone

Custom Configuration

This is completely optional, but in case you want to use custom configurations:

Overwrite existing timezones in the database

By default, the timezone will be overwritten at each login with the current user timezone. This behavior can be restricted to only update the timezone if it is blank by setting the ‘overwrite’ => false, config option.

Lookup Array

This lookup array configuration makes it possible to find the remote address of the user in any attribute inside the Laravel request helper, by any key. Having in mind when the key is found inside the attribute, that key will be used. By default, we use the server attribute with the key REMOTE_ADDR. To override this configuration, you just need to change the lookup property inside the configuration file config/timezone.php for the desired lookup.

Underlying GeoIp Package

If you wish to customise the underlying torann/geoip package you can publish the config file by using the command below.

So, this is pretty how you can use timezone package in your own laravel application following the steps above. It’s one of the most ewasier to use package. Along with that, this package is very efficient.

Reference

Laravel news: Laravel Timezone

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project




    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home