简体   繁体   中英

Laravel 5.2 save user IP adress to DB

I'm trying save user IP adress after login on website. I'm using laravel 5.2 framework. I got user table and login_ip row. My code looks like that:

$user = User::where('login_ip', Request::getClientIp());
$user->save();

But it does not saving. What i'm doing wrong? Sorry for my bad english :)

You can try it as:

auth()->user()->login_ip = Request::getClientIp();
auth()->user()->save();

OR

auth()->user()->save(['login_ip' => Request::getClientIp()]);

Note - It will update the user's login_ip in single query.

Try

$user = User::find(auth()->user()->id);
$user->login_ip = Request::getClientIp();
$user->save();

If you want to save IP for current user, you can do this:

auth()->user()->update(['login_ip' => Request::getClientIp()]);

This will not create additional query as code in shoieb0101 , Amit and Ronald answers.

Don't forget to add login_ip to the $fillable array in User model:

protected $fillable = ['login_ip'];

If you want to save IP for only logged in users and ignore guests, you can do a check:

!auth()->check() ? : auth()->user()->update(['login_ip' => Request::getClientIp()]);

//assuming $userid is also requested

$user = User::where('id', $userid);
$user->login_ip = Request::getClientIp();
$user->save();

You dont have to get logged user form db , all info about your user you have in Auth::user() so:

Auth::user()->login_ip = Request::getClientIp();
Auth::user()->save();

or

Auth::user()->login_ip = $request->ip();
Auth::user()->save();

but you need to have Request $request as parameter of your method.

I am probably stating the obvious, but your first line...

$user = User::where('login_ip', Request::getClientIp());

... returns an Eloquent query builder, right?

So, a save() on this will never work?

$user = User::where('login_ip', Request::getClientIp())->first();

... will return an actual User (if in the DB), which makes save() also possible.

Or did you make a typo in your OP?

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