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 8 dari 12

Membuat Endpoint Riwayat Pesan

Buat controller app/Controllers/Api/Messages.php. Endpoint memvalidasi nama room dan mengambil maksimal 50 pesan terakhir:

public function index(): ResponseInterface
{
    $room = strtolower(trim((string) $this->request->getGet('room')));

    if (! preg_match('/^[a-z0-9_-]{1,50}$/', $room)) {
        return $this->response->setStatusCode(422)->setJSON([
            'message' => 'Nama room tidak valid.',
        ]);
    }

    $model = new MessageModel();
    $messages = $model->where('room', $room)
        ->orderBy('id', 'DESC')
        ->findAll(50);

    return $this->response->setJSON([
        'data' => array_reverse($messages),
    ]);
}