Get User Geographical Location in Laravel
In this short article, we’re going to learn how to get user location in Laravel. Let’s get started:
Table of Contents
Install Package
We’ll use laravel-geoip package. Install the package using this command:
composer require torann/geoip
If you are using Laravel 5.4 or older version, 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 the class. Open up config/app.php
and find the aliases key.
'aliases' => [
......
'GeoIP' => \Torann\GeoIP\Facades\GeoIP::class,
];
Publish the Configurations
Run this on the command line from the root of your project:
php artisan vendor:publish --provider="Torann\GeoIP\GeoIPServiceProvider" --tag=config
A configuration file will be publish to config/geoip.php
. Open the config file and replace:
'cache_tags' => ['torann-geoip-location'],
With:
'cache_tags' => [],
Get Location
Simply use this helper method to get the user location:
$location = geoip("IP_ADDRESS");
dd($location);
Get current user location:
$location = geoip(request()->ip());
dd($location);
Here’s the example location object:
Torann\GeoIP\Location {#323 ▼
#attributes: array:14 [▼
"ip" => "127.0.0.0"
"iso_code" => "US"
"country" => "United States"
"city" => "New Haven"
"state" => "CT"
"state_name" => "Connecticut"
"postal_code" => "06510"
"lat" => 41.31
"lon" => -72.92
"timezone" => "America/New_York"
"continent" => "NA"
"currency" => "USD"
"default" => true
"cached" => false
]
}
Read this doc to know more about this package.
That’s all. Thank you. ?Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (0)