Laravel: Using Cloudflare to Retrieve User Location Information

Learn how to integrate Cloudflare with Laravel to access user location information efficiently.

Laravel: Using Cloudflare to Retrieve User Location Information

May 9, 2024

In this tutorial, we'll demonstrate how to utilize Cloudflare to fetch user location details such as country, city, coordinates, and more.

This functionality is particularly valuable for E-Commerce websites, enabling tasks such as calculating shipping costs and taxes based on the user's country. Additionally, it can be used to block specific actions for certain countries or to simply gather location information for various purposes.

To start, this tutorial assumes that Cloudflare is configured and active on your website. If you haven't set up Cloudflare yet, you'll need to create an account and add your domain on the Cloudflare website.

By default, Cloudflare does not include location-specific information in request headers. To enable this feature, navigate to your Dashboard and select your domain.

Navigate to Rules -> Transform Rules -> Managed Transforms in your Cloudflare dashboard. Scroll down to "HTTP request headers" and enable "Add visitor location headers".

Once enabled, location-specific headers will be added to every request.

 Screenshot of CloudFlare Option to enable

 

To retrieve location information using Laravel requests, you can use the following:

$country = request()->header('CF-IPCountry');
$city = request()->header('CF-IPCity');
$latitude = request()->header('CF-IPLatitude');
$longitude = request()->header('CF-IPLongitude');
$isTorNetwork = request()->header('CF-IPCountry') === 'T1';
$noCountryData  = request()->header('CF-IPCountry') === 'XX';