Laravel location information from IP address

In this example, you will get user location information based on their IP address. You need to install package called stevebauman/location.

The stevebauman/location is an excellent library for detecting a users location by their IP Address. It has ready to use methods for getting user's location data.

With using this package you can get below information :

  • Country Name
  • Country Code
  • Region Name
  • Region Code
  • City Name
  • Zip Code
  • ISO Code
  • Postal Code
  • Metro Code
  • Latitude and Longitude

Install stevebauman/location Package

For Installation you just need to enter below command into terminal.

composer require stevebauman/location

Here, we will use this package using import so we don't need to register into our application.

Create Location Controller

Let's create controller for getting location data and display it using view. First thing you need to enter below command to create controller :

php artisan make:controller LocationController



namespace App\Http\Controllers;

use Stevebauman\Location\Facades\Location; //import
use Illuminate\Http\Request;

class LocationController extends Controller
    public function getLocation(Request $request)
        // $ip = $request->ip(); /*For Actual IP address on Live Server */
        $ip = ''; /* Static IP address */
        $locationInfo = Location::get($ip);
        return view('location-info', compact('locationInfo'))

Here, getLocation() method will get user's IP address from request and get location data. At last, Pass those location to view./p>

If you are running your application is on live server then you need to user $request->ip() method to get information. Here, IP address is defined statically for testing.

Create View

Now, you have location data so you will need a view to display information to user. So create view at views directory and make below changes.


Add Route

In Last Step, thing you need to add route. open route file and make below changes :


use App\Http\Controllers\LocationController;
use Illuminate\Support\Facades\Route;

Route::get('/', function () {
    return view('welcome');

Route::get('get-my-location', [LocationController::class, 'getLocation']);

Testing Our Application / Functionality

Now we are ready to test our functionality. open terminal and run below command :

php artisan serve

Open this URL into browser and it will show location information.

Whenever user hit this URL it will display location data and in addition if location data now found then it will display error message. Generally error raise when you are not running application into production and trying to get IP address using $request->ip().

Share your thoughts

Ask anything about this examples