ром Макаров ром Макаров - 29 days ago 11
MySQL Question

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 :)

Answer

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()]);
Comments