dongshuo9350 2016-02-06 21:38
浏览 23
已采纳

Laravel在注册时获取文件内容并保存到DB

I have this code:

    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'],
        ]);
    }
}

This is register function in laravel controller called AuthController.php

This line 'ip' => $_SERVER['REMOTE_ADDR'], works fine, I'm gettig user's IP. This http://ip-api.com/json/YOURipADDRESS API which detects not only location but also it detects some more stuff based on IP address. I only need to get countryCode from that API and store it to DB. How to do it correctly in this file ?

EDIT

This is my function right now but DB country is empty.

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'],
    ]);
}
  • 写回答

1条回答 默认 最新

  • duanmaduan1848 2016-02-06 21:58
    关注
    $user_details = json_decode(file_get_contents('http://ip-api.com/json/your-ip-address'))
    

    Now you have all details in $user_details as json. You can now use it to store to your DB.

    $user_details->country  //to get country
    

    In your 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;
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 C++ yoloV5改写遇到的问题
  • ¥20 win11修改中文用户名路径
  • ¥15 win2012磁盘空间不足,c盘正常,d盘无法写入
  • ¥15 用土力学知识进行土坡稳定性分析与挡土墙设计
  • ¥70 PlayWright在Java上连接CDP关联本地Chrome启动失败,貌似是Windows端口转发问题
  • ¥15 帮我写一个c++工程
  • ¥30 Eclipse官网打不开,官网首页进不去,显示无法访问此页面,求解决方法
  • ¥15 关于smbclient 库的使用
  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?