PHP Joomla! 6 Joomla! 5 Joomla! 3 (Legacy) Database Basic

Insert a Database Record and Get Its Generated ID with insertObject()

Persists a stdClass directly into a table via $db->insertObject() and automatically populates its primary key property.

Updated on 24 November 2026 41 copies 145 views
components/com_example/src/Model/LeadModel.php
<?php

declare(strict_types=1);

use Joomla\CMS\Factory;
use Joomla\Database\DatabaseInterface;

$db  = Factory::getContainer()->get(DatabaseInterface::class);
$row = (object) [
    'title'   => 'Novo registro',
    'state'   => 1,
    'created' => Factory::getDate()->toSql(),
];

$db->insertObject('#__example_items', $row, 'id');
$newId = (int) $row->id;
Passing the primary key name as the third argument populates $row->id automatically.
components/com_example/src/Model/LeadModel.php
<?php
$db = JFactory::getDbo();
$row = new stdClass();
$row->title   = 'Novo registro';
$row->created = JFactory::getDate()->toSql();
$db->insertObject('#__example_items', $row, 'id');
$newId = $row->id;
Legacy Joomla 3 version via JFactory::getDbo().

Technical explanation and best practices

For lightweight inserts such as audit logs or metrics outside a full Table class, $db->insertObject('#__table', $row, 'id') handles quoting automatically and writes the generated auto-increment ID directly into $row->id.

Direct Engineering

Have a Joomla project or technical challenge in mind?

From architectural diagnosis to production deployment, directly with the engineer.