dousui7410 2016-02-28 06:38
浏览 97
已采纳

如何使用Laravel 5.2在eloquent create方法中自动包含Request() - > ip()中的客户端IP地址?

I have this set of eloquent model:

    class UserModel extends Model
    {
        protected $fillable = array(
                'first_name',
                'last_name',
                'email',
                'password',
                'ip',
            );

        protected $table = 'users';
    }

The idea is... I want to include the ip address of the client whenever he/she register as user on our site.

In Laravel 5.2, we can retrieve the client ip address using the Request() class

Request()->ip()

https://laravel.com/api/5.2/Illuminate/Http/Request.html#method_ip

When creating a user record using eloquent model, I use the create() method so I don't have to do the work around for us in assigning values of each field EXCEPT for the 'IP' field.

Is there any ways to automatically assigned the 'IP' field from UserModel with the value coming from Request()->ip() method?

public function createNewUser(Request $request) {

    return  $this->user->create($request->all());
}

Any suggestions/feedbacks would be appreciated.

Thanks!

  • 写回答

2条回答 默认 最新

  • douci1851 2016-02-28 06:55
    关注

    How about something like this:

    public function createNewUser(Request $request) {
    
        $requestArr = $request->all();
        $requestArr['ip'] = $request()->ip();
        return  $this->user->create($requestArr);
    }
    

    OR

    public function createNewUser(Request $request) {
    
        return  $this->user->create(array_push($request->all(), array('ip' => $request()->ip())));
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 spring后端vue前端
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题