CakePHP でユーザーの「最終ログイン日時」をセットする

「ユーザーがログインしたらデータベースに最終ログイン日時をセットする」という処理を実装してみました。 users テーブルに last_login フィールドを DATETIME 型で作成していることを前提としています。

<?php
// app_controller.php
function beforeFilter() {
    $this->loginRedirect = array('controller' => 'users', 'action' => 'index', 'admin' => true);
    $this->autoRedirect = false;
}

loginRedirect でログイン後のリダイレクト先を指定しています。 autoRedirect を false にすることによって、ログイン後のリダイレクトが無効になり、login アクション内の処理が実行されるようになります。

<?php
// controllers/users_controller.php
function login() {
    $userId = $this->Auth->user('id');
    if (!empty($this->data)) {
        if ($userId) {
            $this->User->updateLastLogin($userId);
            $this->redirect($this->Auth->redirect());
        }
    } else {
        if ($userId) {
            $this->redirect($this->Auth->redirect());
        }
    }
}

ユーザー名とパスワード($this->data)が入力されており、ログインに成功している(id が取得できた)場合は、User モデルの updateLastLogin に id をパラメーターとして渡します。 その後、AppController の loginRedirect で指定したアクションにリダイレクトしています。

ログイン状態で /users/login を表示するなど、ユーザー名とパスワードが空でログインに成功している場合は、ログイン画面を表示させる必要が無いので、同じように loginRedirect で指定したアクションにリダイレクトしています。

<?php
// models/user.php
function updateLastLogin($id) {
    $this->id = $id;
    $data = array(
            'last_login' => date('Y-m-d H:i:s'),
            'modified' => false
            );
    return $this->save($data);
    }

モデルの updateLastLogin() にて、データを更新します。 なぜ modified を false にしているのかというと、ログイン日時を更新する時に、modified フィールドも更新されてしまうためです。 false にすると modified フィールドは更新されなくなります。

ログイン日時と更新日時は別々にした方が良いと思ったのでこうしました。 更新日時も更新されて良いのであれば、以下のような書き方でも良いと思います。

<?php
// models/user.php
function updateLastLogin($id) {
    $this->id = $id;
    return $this->saveField('last_login', date('Y-m-d H:i:s'));
}

割と簡単に実装することができました。

© 2023 暇人じゃない. All rights reserved.