[英]how to get country from ip in Laravel
I have Creates custom Analytics Module, Where I can track the Visitor Activity, Here I used the Laravel Package "stevebauman/location" for getting Visitor Location.我创建了自定义分析模块,我可以在其中跟踪访客活动,在这里我使用 Laravel Package“stevebauman/location”来获取访客位置。
The main issue is that, when I statically provide the IP to the Variable, this ip provided me the correct location.主要问题是,当我向变量静态提供 IP 时,这个 ip 为我提供了正确的位置。 on the other hand, When I get IP dynamically.
另一方面,当我动态获得 IP 时。 It just provide the IP
它只提供 IP
$visitor = request()->ip();
How Can I get country Name, Code, Postal Address from the IP in Laravel如何从 Laravel 中的 IP 获取国家名称、代码、邮政地址
$visitor = request()->ip();
$traffic = PageVisits::where('ip_address', $visitor)->where('property_id', $id)
->whereMonth('created_at', Carbon::now()->month)->first();
if(auth()->check() && auth()->user()->usertype == 'Admin'){
}else{
if (!$traffic) {
$traffic = new PageVisits();
$traffic->ip_address = $visitor;
$traffic->property_id = $id;
$position = Location::get('https://'.$visitor);
$traffic->country = $position->countryName;
$traffic->agency_id = $property->agency_id ?? '';
$traffic->save();
}
您可以创建一个服务,然后可以在您的控制器中使用该服务。
You Can Create Folder With service and but it >>>> I use apiStack您可以使用服务创建文件夹,但它 >>>> 我使用 apiStack
<?php
namespace App\Services;
use Illuminate\Support\Facades\Http;
class IpStack
{
protected $key;
protected $baseUrl = 'http://api.ipstack.com/';
public function __construct($key)
{
$this->key = $key;
}
public function get($ip)
{
// http://api.ipstack.com/(ip)?access_key=(key)
$response = Http::baseUrl($this->baseUrl)
->get($ip, [
'access_key' => $this->key,
]);
return $response->json();
}
}
for call in controller拨打电话 controller
{
$geoip = new IpStack(config('services.ipstack.key'));
$response = $geoip->get(request()->ip());
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.