In this tutorial, i’ll show you how to add multiple timezones functionality into your laravel application.

Dates must be presented to a guest or user in his local timezone so it’s better to store those in UTC timezone (default in laravel).

So when visitor come to the website we have to get his local timezone and to solve this problem, we need to install laravel-geoip package.

To install it run the commande line

Once installed you need to register the service provider with the application. Open upΒ config/app.phpΒ and find theΒ providersΒ key.

This package also comes with an optional facade, which provides an easy way to call the the class. Open upΒ config/app.phpΒ and find the aliases key.

Run this on the command line:

A configuration file will be publish toΒ config/geoip.php.

 

While using the library, it can be possible you will get the error β€˜This cache store does not support tagging’ with BadMethodCallException. If so, just change the below line fromΒ config/geoip.phpΒ file.

 

Replace

With

 

Great ! now Geoip is ready and we can get geographical location of visitors based on their IP addresses.

Now we have to store timezone visitor in cookie. Let’s create middleware

We have to exclude encryption for timezone cookie. go to app/Http/Middleware/EncryptCookies.php file and add timezone to except array.

Read Also  Send Email with Attachment in Laravel

Add middleware to kernel app/Http/Kernel.php.

 

Okey, now for example we have news model contains title, content, published_at, created_at, updated_at. So if we want to show the date based on user timezone it’s very easy.

To convert date we have to use accessors and mutators. for more information about accessors and mutators in laravel read this https://laravel.com/docs/5.8/eloquent-mutators

After you create news model and the migration, now we have to edit news model.

 

Great !, now published_at, created_at, updated_at attributes when we add or edit, the dates will be converted to UTC timezone and when we retrieve them they will be converted to local timezone user. For example

Read Also  Laravel Timestamps tricks

 

If you want to save and retieve timezone from user table, you need to add timezone field in user table.

 

Also we have to edit TimezoneMiddleware.

In middleware

 

That’s it!. I hope you got to know how to add multiple timezones functionality into your laravel website.


    No Comments

    Leave a Reply

    your email address will not be published. required fields are marked *

    *
    *