Pages

14 January, 2021

How to create logs in Laravel & Store last login

 





        <?php 

        1. How to create logs in Laravel & Store last login  // 1

        Quick tip of the day. Default Laravel Auth comes with User table and model,
        but without logging capability, so we need to build it ourselves. Fortunately,
        it’s very easy, I will show you one method.

        Let’s say that we want to save user’s last login time and IP address in the same users table.
        So we start with database migration:

        ## /* php artisan make:migration add_login_fields_to_users_table*/##

        Then we fill it with these fields:

        class AddLoginFieldsToUsersTable extends Migration
        {

            public function up()
            {
                Schema::table('users'function (Blueprint $table) {
                    $table->datetime('last_login_at')->nullable();
                    $table->string('last_login_ip')->nullable();
                });
            }

            // ...
        ?>

        Next, we need to add these fields as fillables in app/User.php model:

        Next, we need to add these fields as fillables in app/User.php model:

        <?php 
        class User extends Authenticatable
        {
            protected $fillable = [
                'email',
                'password',
                'name',
                'last_login_at',
                'last_login_ip',
            ];

            // ...
        Finally, how do we fill them in? You need to know that there is authenticated() method
        in the AuthenticatesUsers trait. It’s called every time someone logs in.

        /**
         * The user has been authenticated.
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  mixed  $user
         * @return mixed
         */
        protected function authenticated(Request $request, $user)
        {
            //
        }
        In trait this method is empty. So we have freedom to override it in LoginController
        and add whatever code we need.

        app/Http/Controllers/Auth/LoginController.php:

        function authenticated(Request $request, $user)
        {
            $user->update([
                'last_login_at' => Carbon::now()->toDateTimeString(),
                'last_login_ip' => $request->getClientIp()
            ]);
        }
        And, that’s it! Here’s what we have in users table after log in:

        ?>


No comments:

Post a Comment

Thanks