Add last login date to users in laravel5


Lately i wanted to add last login date to users to track when they last logged in order to know the active users and the inactive users.
I didn’t find good tutorial on how to do that in laravel5 so i decided to do my own tutorial , so prepare your self and lets do some coding
– first step is to modify the user table so lets make a migration for that
php artisan make:migration add_lastlogin_to_users_table
then lets add the column wee need “lastlogin_at“
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class AddExtraFieldsToUsers extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::table('users', function ($table) {
            $table->dateTime('lastlogin_at');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::table('users', function ($table) {
            $table->dropColumn('lastlogin_at');
        });
    }
}
ok we are good lets run the migration
php artisan migrate

 
the next step is to update that field each time user logged in , there is number of ways to do that , you can add event to listen to Auth.login and fire your own code but lets make it simple and modify the AuthController
if you look into your AuthController you will find it simple and it inherit most of major functionality from Illuminate\Foundation\Auth\AuthenticatesAndRegistersUsers;
laravel knows that we cannot modify the vendor source code so they provide something like callback functions to help us customize the functionality
one of this function is “authenticated” which called if it exists after the user is authenticated successfully.
so lets write it in our AuthController
  function authenticated(Request $request,User $user){
      $user->lastlogin_at = date('Y-m-d H:i:s');
      $user->save();
      return redirect()->intended($this->redirectPath());
  }
as you see it take the $request param which is instance of Request and $user which is instance of authenticated User.
now all set every user logged you can track it
regards and happy coding

Comments

Popular Posts