我有这个代码:
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'ip' => $_SERVER['REMOTE_ADDR'],
'country' => 'http://ip-api.com/json/'.$_SERVER['REMOTE_ADDR'],
'password' => bcrypt($data['password']),
'secret_question' => $data['secret_question'],
'question_answer' => $data['question_answer'],
]);
}
}
这是 laravel 控制器中的注册函数,称为 AuthController.php
这条线'ip' => $_SERVER['REMOTE_ADDR'],
工作正常,我是gettig用户的IP。这个 http://ip-api.com/json/YOURipADDRESS API不仅可以检测位置,还可以根据IP地址检测更多内容。我只需要从该 API 获取countryCode
并将其存储到数据库中。如何在此文件中正确执行此操作?
编辑
这是我现在的函数,但 DB 国家是空的。
protected function create(array $data)
{
$user_details = json_decode(file_get_contents('http://ip-api.com/json/'.$_SERVER['REMOTE_ADDR']));
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'ip' => $_SERVER['REMOTE_ADDR'],
'country' => $user_details->country,
'password' => bcrypt($data['password']),
'secret_question' => $data['secret_question'],
'question_answer' => $data['question_answer'],
]);
}
$user_details = json_decode(file_get_contents('http://ip-api.com/json/your-ip-address'))
现在,您将所有详细信息都$user_details
为 json。您现在可以使用它来存储到您的数据库。
$user_details->country //to get country
在你的AuthController.php
protected function create(array $data)
{
return User::create([
'name' => $data['name'],
'email' => $data['email'],
'ip' => $_SERVER['REMOTE_ADDR'],
'country' => $this->getCountry($_SERVER['REMOTE_ADDR']),
'password' => bcrypt($data['password']),
'secret_question' => $data['secret_question'],
'question_answer' => $data['question_answer'],
]);
}
protected function getCountry($ip)
{
return json_decode(file_get_contents('http://ip-api.com/json/your-ip-address'))->country;
}