Laravel has an amazing authentication system. Everything comes out of the box unless you want some changes to the original system. In this article, we are going to twist a little bit of laravel authentication system for adding more fields i.e. user last login time and IP address.
I guess you have already laravel project with laravel default authentication system. If not, you can create an authentication system by running the command below:
php artisan make: auth
Laravel comes with default users table migration and model. So, we will add two fields to this table.
php artisan make:migration add_login_time_fields_to_users_table
After this, we will add two columns in migration.
public function up() { Schema::table('users', function (Blueprint $table) { $table->datetime('last_login_at')->nullable(); $table->string('last_login_ip')->nullable(); }); }
Let’s migrate our newly created migration file using artisan command:
php artisan migrate
Okay! now we need to add these two columns fillable in User model. Simply, open up the User
model and modify fillable as below:
protected $fillable = [ 'name', 'email', 'password', 'last_login_at', 'last_login_ip', ];
Finally, setting up is done. Now, it’s time to fill up those columns. If you have noticed earlier, there is a authenticated()
function in lluminate\Foundation\Auth\AuthenticatesUsers
trait. This function is called everytime a user is authenticated. The authenticated user and request are already passed. We just need to save the information.
After modifying the function, our code looks like below:
protected function authenticated(Request $request, $user) { $user->update([ 'last_login_at' => Carbon::now()->toDateTimeString(), 'last_login_ip' => $request->getClientIp() ]); }
Howdy! we are done. Now, we we look our database, we will see the last login time and IP address of users that are once logged in.