CakePHP 4 Audit Log Plugin
Asyraf Wahi Anuar - December 01, 2021Estimated reading time: 1 minute, 52 seconds

An audit trail (audit logs) is a chronological log meant to capture any changes made to the electronic contents. The logs are used to be evidence for any changes that affected the contents. Rather than acting as evidence, audit logs are also used to support versioning for each content. To integrate the audit trails in CakePHP based web application, a CakePHP Audit Log Plugin can be used.
Repository URL: https://github.com/hevertonfreitas/cakephp-audit-log
Installation
Download the plugin using composer:
composer require hevertonfreitas/cakephp-audit-log
Load Plugin
bin/cake plugin load AuditLog
or manually load the plugin in .../src/Application.php.
$this->addPlugin('AuditLog');
Database Table Migration
Execute the following command to run the table migration. This process will generate two tables i)audits; ii)audit_deltas.
bin/cake migrations migrate -p AuditLog
or manually create the table:
CREATE TABLE `audits` (
`id` char(36) NOT NULL,
`event` varchar(255) NOT NULL,
`model` varchar(255) NOT NULL,
`entity_id` varchar(255) NOT NULL,
`json_object` text DEFAULT NULL,
`description` text DEFAULT NULL,
`source_id` varchar(255) DEFAULT NULL,
`created` datetime NOT NULL,
`delta_count` int(11) NOT NULL DEFAULT 0,
`source_ip` varchar(255) DEFAULT NULL,
`source_url` varchar(255) DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
CREATE TABLE `audit_deltas` (
`id` char(36) NOT NULL,
`audit_id` char(36) NOT NULL,
`property_name` varchar(255) NOT NULL,
`old_value` text DEFAULT NULL,
`new_value` text DEFAULT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
ALTER TABLE `audits`
ADD PRIMARY KEY (`id`);
ALTER TABLE `audit_deltas`
ADD PRIMARY KEY (`id`);
AuditLog Behavior
Add AuditLog behaviour in your specific model. In this tutorial, I used the Article table which can be found at .../src/Model/Table/ArticlesTable.php
public function initialize(array $config): void
{
parent::initialize($config);
...
$this->addBehavior('AuditLog.Auditable', [
'ignore' => ['created'],
//'habtm' => ['Tags'],
]);
}
At this point, the AuditLog will capture all changes made to the contents.
To capture the id, ip, URL and description, add the following code in the model:
use Cake\Routing\Router; //at top of your model table
...
public function currentUser(): array
{
return [
'id' => '15',
'ip' => Router::getRequest()->clientIp(),
'url' => Router::url(null, true),
'description' => 'Testing audit log',
];
}
For easy references, bake the audits table so that you can view the audit log.
That's all. Happy coding :)






