การทำระบบ users login logs เพื่อเก็บข้อมูลและสถิติการเข้าใช้งานระบบของผู้ใช้
การทำงานโดยรวมนั้น เริ่มจากการที่ระบบของเรามีฐานข้อมูลและมีตารางชื่อ user สำหรับเก็บข้อมูลผู้ใช้อยู่แล้ว ดังนั้นเราจะเพิ่มความสามารถบางอย่างเข้าไป เพื่อดึงข้อมูลของผู้ใช้แต่ละคนที่มีการล็อกอินเข้าสู่ระบบ จากนั้นนำข้อมูลใหม่ไปเก็บลงในอีกตารางเพื่อนำข้อมูลไปใช้ ต่อไป โดยมีขั้นตอนดังนี้
1. ทำการสร้างตารางใหม่เพิ่มเข้าไปในฐานข้อมูลเดิม โดยใช้คำสั่ง
php artisan make:migration create_authentication_logs_table
2. เปิดไฟล์ authentication_logs จากโฟลเดอร์ database/migrations ใส่ข้อมูลฟิลด์ที่ต้องการ ดังนี้
public function up()
{
Schema::create('authentication_logs', function (Blueprint $table) {
$table->id();
$table->foreignId('user_id')->constrained()->onDelete('cascade');
$table->string('ip_address', 45)->nullable();
$table->text('user_agent')->nullable();
$table->timestamp('login_at')->useCurrent();
// You can add more, like 'location' or 'device'
});
}
3. ใช้คำสั่งนำเข้าตารางและฟิลด์เข้าสู่ฐานข้อมูล
php artisan migrate
4.ใช้คำสั่งบน terminal สร้างตัว Listener
php artisan make:listener LogSuccessfulLogin
5. เปิดไฟล์ listener จากโฟลเดอร์ app/Listeners/LogSuccessfulLogin.php เพิ่มข้อมูลให้เหมือนดังโค้ดด้านล่าง
namespace App\Listeners;
use Illuminate\Auth\Events\Login;
use Illuminate\Support\Facades\DB;
use Illuminate\Http\Request;
class LogSuccessfulLogin
{
protected $request;
public function __construct(Request $request)
{
$this->request = $request;
}
public function handle(Login $event)
{
DB::table('authentication_logs')->insert([
'user_id' => $event->user->id,
'ip_address' => $this->request->ip(),
'user_agent' => $this->request->userAgent(),
'login_at' => now(),
]);
}
}
6. เปิดไฟล์เช็คความสมบูรณ์ส่วนสำคัญก่อนใช้งาน สำหรับ Laravel ตั้งแต่เวอร์ชั่น 11 ขึ้นไปเช็คใน app/Providers/AppServiceProvider.php หรือ app/Providers/EventServiceProvider.php ให้มีข้อมูลดังนี้
use Illuminate\Support\Facades\Event;
use Illuminate\Auth\Events\Login;
use App\Listeners\LogSuccessfulLogin;
public function boot(): void
{
Event::listen(
Login::class,
LogSuccessfulLogin::class,
);
}
ในที่นี้ใช้ Laravel 12 จะได้ดังโค้ดด้านบน ในไฟล์ app/Providers/EventServiceProvider.php
7.เพียงเท่านี้ก็สามารถใช้งานได้แล้ว ทดสอบเปิดโปรเจ๊กขึ้นมาแล้วล็อกอินเข้าสู่ระบบ เมื่อเข้าระบบได้แล้วให้เปิดตาราง authentication_logs จะพบข้อมูลผู้เข้าใช้งานถูกเก็บลงในตารางโดยอัตโนมัติทันที
