Physical Address
304 North Cardinal St.
Dorchester Center, MA 02124
In this tutorial, I will give you an example of “How to get the complete user location in laravel 8”, So you can easily apply it with your laravel 5, laravel 6, laravel 7, and laravel 8 application.
The simple need to collect the user information because of analytics tracking user traffic and also for future scope.
Here is the complete list of location information that we are going to get based on IP address in the laravel app using the Torann-geoip-location Package:
Get location information using IP address in the laravel 8 application using location package :
Lets start from Scratch :
Migration Structure
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;
class CreateUsersTable extends Migration
{
/**
* Run the migrations.
*
* @return void
*/
public function up()
{
Schema::create('users', function (Blueprint $table) {
$table->id();
$table->string('name');
$table->string('email')->unique();
$table->timestamp('email_verified_at')->nullable();
$table->string('password');
$table->longText('geoipInfo');
$table->rememberToken();
$table->timestamps();
});
}
/**
* Reverse the migrations.
*
* @return void
*/
public function down()
{
Schema::dropIfExists('users');
}
}
Run Migration
php artisan migrate
App\Models\User.php
<?php
namespace App\Models;
use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
class User extends Authenticatable
{
use HasFactory, Notifiable;
/**
* The attributes that are mass assignable.
*
* @var array
*/
protected $fillable = [
'name',
'email',
'password',
'geoipInfo',
];
/**
* The attributes that should be hidden for arrays.
*
* @var array
*/
protected $hidden = [
'password',
'remember_token',
];
/**
* The attributes that should be cast to native types.
*
* @var array
*/
protected $casts = [
'email_verified_at' => 'datetime',
];
}
Install torann-geoip-location Package
This package helps us to determine the geographical location of website visitors based on their IP addresses in the Laravel application.
Open the project into the terminal and run this command to install it.
composer require torann/geoip
Update Config File :
You need to update your app.php file inside the same config\app.php directory where you need to add the providers and aliases of the package as shown below.
config\app.php
'providers' => [
....
....
....
Torann\GeoIP\GeoIPServiceProvider::class,
],
'aliases' => [
....
....
....
'GeoIP' => \Torann\GeoIP\Facades\GeoIP::class,
]
Update GeoIP Config File :
config\geoip.php
'cache' => 'all',
/*
|--------------------------------------------------------------------------
| Cache Tags
|--------------------------------------------------------------------------
|
| Cache tags are not supported when using the file or database cache
| drivers in Laravel. This is done so that only locations can be cleared.
|
*/
// 'cache_tags' => ['torann-geoip-location'],
'cache_tags' => [],
/*
|--------------------------------------------------------------------------
| Cache Expiration
|--------------------------------------------------------------------------
|
| Define how long cached location are valid.
|
*/
'cache_expires' => 30,
Create a Controller
php artisan make:controller GeoIpExampleController
routes\web.php
<?php
use Illuminate\Support\Facades\Route;
use App\Http\Controllers\GeoIpExampleController;
Route::get('/user-list', [GeoIpExampleController::class,'index'])->name('user.list');
Route::get('/user-create', [GeoIpExampleController::class,'create']);
Route::post('/user-register', [GeoIpExampleController::class,'register'])->name('user.register');
app\Http\Controllers\GeoIpExampleController.php
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use\App\Models\User;
use Auth;
use Illuminate\Support\Facades\Hash;
class GeoIpExampleController extends Controller
{
public function index(){
$data = User::get();
return view('geoIplocation.list',compact('data'));
}
public function create(){
return view('geoIplocation.register');
}
public function register(Request $request){
$geoipInfo = geoip()->getLocation(\Request::ip());
$request->validate([
'name' => 'required',
'email' => 'required|email|unique:users',
'password' => 'required|min:6',
]);
$usersignup = new User;
$usersignup->name = $request->name;
$usersignup->email = $request->email;
$usersignup->password = Hash::make($request->password);
//Encode Geo data as Json Format
$usersignup->geoipInfo = json_encode(['ip'=>$geoipInfo['ip'],'iso_code'=>$geoipInfo['iso_code'],'country'=>$geoipInfo['country'],'city'=>$geoipInfo['city'],'state'=>$geoipInfo['state'],'state_name'=>$geoipInfo['state_name'],'postal_code'=>$geoipInfo['postal_code'],'lat'=>$geoipInfo['lat'],'lon'=>$geoipInfo['lon']]);
$usersignup->save();
return redirect()->route('user.list');
}
public function ViewData($id){
$data = Test::where('id',$id)->first();
return view('jsonexample.view',compact('data'));
}
}
$geoipInfo = geoip()->getLocation(\Request::ip());
dd($geoipInfo);
Note: You get the exact location of the user while your web application is live on a server.
We get the registered user’s complete information, we store complete information in JSON format in geioipinfo column in our user’s table.
Recommended article: Save Multiple Columns Data into Single Column in Laravel.
resources\views\geoIplocation\register.blade.php
<div class="container">
<div class="row justify-content-center">
<div class="col-lg-6">
<div class="main">
<h3>Access User Location information with IP address in Laravel</h3>
<form role="form" action="{{route('user.register')}}" method="post">
@csrf
<div class="form-group">
<label for="userename">Name <span class="text-danger">*</span></label>
<input type="text" name="name" class="form-control">
@if ($errors->has('name'))
<span class="text-danger">{{ $errors->first('name') }}</span>
@endif
</div>
<div class="form-group">
<label for="useremail">Email <span class="text-danger">*</span></label>
<input type="email" name="email" class="form-control">
@if ($errors->has('email'))
<span class="text-danger">{{ $errors->first('email') }}</span>
@endif
</div>
<div class="form-group">
<label for="userpassword">Password <span class="text-danger">*</span></label>
<input type="password" name="password" class="form-control">
@if ($errors->has('password'))
<span class="text-danger">{{ $errors->first('password') }}</span>
@endif
</div>
<div class="form-group">
</div>
<button type="submit" class="btn btn btn-secondary">
Register
</button>
</form>
</div>
</div>
</div>
</div>
resources\views\geoIplocation\list.blade.php
<div class="container">
<hr>
<h3>Access User Location information with IP address in Laravel:</h3>
<hr>
<br>
<table class="table">
<thead>
<tr>
<th>S.no</th>
<th>Name</th>
<th>Email</th>
<th>IP</th>
<th>ISO</th>
<th>Country</th>
<th>City</th>
<th>State code</th>
<th>State</th>
<th>Postal</th>
<th>Latitude</th>
<th>Longitude</th>
</tr>
</thead>
<tbody>
@foreach($data as $key => $data)
<tr>
<td>{{ $key+1 }}</td>
<td>{{ $data->name }}</td>
<td>{{ $data->email }}</td>
<!-- Decode json data -->
@php $geoInfo = json_decode($data->geoipInfo,true); @endphp
<td>{{$geoInfo['ip']}}</td>
<td>{{$geoInfo['iso_code']}}</td>
<td>{{$geoInfo['country']}}</td>
<td>{{$geoInfo['city']}}</td>
<td>{{$geoInfo['state']}}</td>
<td>{{$geoInfo['state_name']}}</td>
<td>{{$geoInfo['postal_code']}}</td>
<td>{{$geoInfo['lat']}}</td>
<td>{{$geoInfo['lon']}}</td>
</tr>
</tbody>
@endforeach
</table>
</div>
In this article, we learned “How to get the complete user location in laravel 8”, I hope this article will help you with your Laravel application Project.
Also Read: Generate Barcode in Laravel 8.