How to Use IP2Location Database in Laravel Framework
ip2location facebbook  ip2location twitter  ip2location google+ ip2location github

How to Use IP2Location Database in Laravel Framework

Laravel Framework

This tutorial shows you on how to import IP2Location DB3 (IP-Country-Region-City) into a MySQL database server and retrieve the geolocation information for viewing.

First of all, we assumed that the Laravel Framework and MySQL database server had been properly set up before following this tutorial.

  1. Download the IP2Location DB3 (IP-Country-Region-City) database from

  2. Unzip the file and you shall find the IP-COUNTRY-REGION-CITY.CSV file.
    Laravel Framework

  3. Create ip2location database and ip2location_db3 table in MySQL with the following SQL command:

    		CREATE DATABASE ip2location
    		USE ip2location;
    		CREATE TABLE `ip2location_db3`(
    			`ip_from` INT(10) UNSIGNED,
    			`ip_to` INT(10) UNSIGNED,
    			`country_code` CHAR(2),
    			`country_name` VARCHAR(64),
    			`region_name` VARCHAR(128),
    			`city_name` VARCHAR(128),
    			INDEX `idx_ip_from` (`ip_from`),
    			INDEX `idx_ip_to` (`ip_to`),
    			INDEX `idx_ip_from_to` (`ip_from`, `ip_to`)
  4. Import the CSV data into ip2location_db3 table.

    			INTO TABLE`ip2location_db3`
    			ENCLOSED BY '"'
    			LINES TERMINATED BY '\r\n';
  5. This will complete the IP2Location geolocation database set up. Now, we will move on the Lavarel framework part.

  6. Open the Lavarel database configuration file at config/database.php and update the connection information to your MySQL database.
    Laravel Framework

  7. Create a UserController.php class at app/Http/Controllers folder with the below codes.
  8. <?php
    namespace App\Http\Controllers;
    use DB;
    use App\User;
    use App\Http\Controllers\Controller;
    class UserController extends Controller
        public function getIPLocation($ip_address)
            $result = DB::select('SELECT * FROM `ip2location_db3` WHERE INET_ATON(?) <= ip_to LIMIT 1', array($ip_address));
            return $result;
  9. We created one function named as getIPLocation that will accept an ip_address parameter for location lookup. And, this function will returns the location result to the caller.

  10. Next, we need to add the routing into app/Http/routes.php for the above controller class. Open the routes.php file and add the below code.

  11. Route::get('ip/{ip_address}', 'UserController@getIPLocation');
  12. The above code will basically accept the ip/{ip_address} in url and pass the control to getIPLocation function inside UserController class for location retrieval.

  13. After that, you may try the solution by entering the url : http://YOUR_DOMAIN/ip/

  14. You shall see the result as below:
    Laravel Framework

Do you like this article? Share it with others by clicking the social media buttons below. We will write more articles related to this topic.