How to get a user location in Laravel 7
In this shot, you will learn how to get a user’s location, specifically the country. You can also get other location information from the users, but in this shot we will just be touching on the country.
Step 1: Install a composer package
First, you have to install a composer package called SteveBaumer. Install the composer package like so:
composer require stevebauman/location
Step 2: Publish the configuration file
Run this artisan command, which will create a location.php file in your config directory.
php artisan vendor:publish --provider="Stevebauman\Location\LocationServiceProvider"
Step 3: Usage
From the controller where you want implement the location logic, you can write a function. In this shot we will use a countryLocation() function.
public function countryLocation(Request $request){
$location = Location::get($request->ip());
dd($location->countryName);
}
The code above uses the get($request->ip()) method to get the location of the user, with the user’s IP address on the Location facade.