Sistem Berbasis Website

Contoh Aplikasi Chat Realtime dengan Ratchet, MySQL, Bootstrap, CSS, dan CodeIgniter 4

Tutorial membuat aplikasi chat realtime CodeIgniter 4 menggunakan Ratchet WebSocket, MySQL, Bootstrap, CSS, dan JavaScript lengkap dengan source code.

Contoh coding Contoh Aplikasi Chat Realtime dengan Ratchet, MySQL, Bootstrap, CSS, dan CodeIgniter 4
Langkah 4 dari 12

Membuat Migration dan Model Pesan

Buat migration:

php spark make:migration CreateChatMessages

Tabel menyimpan room, ID browser, nama pengguna, isi pesan, dan waktu pengiriman:

$this->forge->addField([
    'id' => [
        'type' => 'BIGINT', 'constraint' => 20,
        'unsigned' => true, 'auto_increment' => true,
    ],
    'room' => ['type' => 'VARCHAR', 'constraint' => 50],
    'client_id' => ['type' => 'VARCHAR', 'constraint' => 64],
    'user_name' => ['type' => 'VARCHAR', 'constraint' => 60],
    'message' => ['type' => 'TEXT'],
    'created_at' => ['type' => 'DATETIME'],
]);
$this->forge->addKey('id', true);
$this->forge->addKey(['room', 'created_at']);
$this->forge->createTable('chat_messages');

Jalankan:

php spark migrate

Buat app/Models/MessageModel.php:

class MessageModel extends Model
{
    protected $table = 'chat_messages';
    protected $primaryKey = 'id';
    protected $returnType = 'array';
    protected $protectFields = true;
    protected $allowedFields = [
        'room', 'client_id', 'user_name', 'message', 'created_at'
    ];
    protected $useTimestamps = false;
}