简体   繁体   中英

How to automatically include client ip address from Request()->ip() in eloquent create method using Laravel 5.2?

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!

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())));
}

After some digging on the web, I found the sure way to do this stuff.

public function createNewUser(Request $request) {

    $request->request->add(['ip' => $request->ip()]);

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

The answer provided by @AlexeyMezenin would also work somehow but you have to do some little extra code for it to work. Thanks anyway.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM