Best way to show website language based on visitor location
If you are making your website using laravel and finding the solution to translate your website for multiple languages, you can follow this post 4 simple steps to make your website support multi-languages in laravel and as a result, you will get a beautiful website with multiple languages supported. if you want to go beyond this technique which enables the ability of your website to recognize the user geographic location and showing the content with respective language to visitors, you can follow the below simple techniques.
Ok, now let's start the tips to show your website to visitors based on their location. For example, you are viewing the website from Cambodia so the website should display content in Khmer language or display in Chinese if visitors view the website from China. The website which implements this feature tends to have more visitors to re-visit the site again and gain more popularity than the website that has only one language support. Eg. Apple, Microsoft, Facebook always come with this multi-languages support and show personalized content to their users. As you may think this is not a big deal, but this is a big deal.
STEP 1: Finding Visitor IP Address
We will start by adding package laravel-geoip into our project to help us determine the user's location based on their IP address
$ composer require torann/geoip
Once installed you need to register the service provider with the application. Open up config/app.php
and find the providers
key.
'providers' => [
\Torann\GeoIP\GeoIPServiceProvider::class,
]
This package also comes with an optional facade, which provides an easy way to call the class. Open up config/app.php
and find the aliases key.
'aliases' => [
'GeoIP' => \Torann\GeoIP\Facades\GeoIP::class,
];
Publish the package's configuration file by running the following command will generate a geoip.php file in the config folder. After that, we can now customize the package's behavior in the project.
php artisan vendor:publish --provider="Torann\GeoIP\GeoIPServiceProvider" --tag=config
There is an important configuration needed to change in this package to get work out of the box. You have to change key "cache_tags" as below
'cache_tags' => [],
STEP 2: Setting Localization Based on User Location
Now we can start to change localization middleware to support the geo IP address of visitors
There are a few things happening in the above function code. We cover a few scenarios as below:
- We have a predefined list of supported countries and their respective languages
- We fetch the visitor's IP address and the country based on the IP address using an additional package called laravel-geoip
- If the user's country is among the supported countries, we set the application's language to the visitor's language.
- If the user is not from the supported country, we set to default the English language.
THANK YOU !!!!