cakephp/database
CakePHP Database provides a flexible database abstraction layer with a powerful query builder, schema and type system, connection management, and drivers for common SQL databases. Use it standalone or within CakePHP to build and run queries cleanly.
To integrate cakephp/database into a Laravel project, follow these steps:
Installation
composer require cakephp/database
Basic Connection Setup
Create a connection configuration in config/database.php (or extend Laravel’s config):
'connections' => [
'cakephp' => [
'driver' => 'cakephp',
'host' => env('DB_HOST', 'localhost'),
'username' => env('DB_USER', 'forge'),
'password' => env('DB_PASSWORD', ''),
'database' => env('DB_DATABASE', 'forge'),
'prefix' => env('DB_PREFIX', ''),
'encoding' => 'utf8mb4',
'timezone' => '+00:00',
'flags' => [],
],
],
First Query Use the PDO-like API in a service or controller:
use Cake\Database\Connection;
$connection = Connection::connect([
'dsn' => 'mysql://user:pass@localhost/dbname',
]);
$users = $connection->fetchAll('SELECT * FROM users WHERE active = 1');
Laravel Service Provider
Bind the connection to Laravel’s IoC container in AppServiceProvider:
public function register()
{
$this->app->singleton('cakephp.db', function ($app) {
return Connection::connect(config('database.connections.cakephp'));
});
}
Leverage the familiar PDO methods for queries, prepared statements, and transactions:
// Prepared statements
$stmt = $connection->prepare('INSERT INTO posts (title) VALUES (:title)');
$stmt->bindValue('title', 'Hello CakePHP!');
$stmt->execute();
// Transactions
$connection->begin();
try {
$connection->execute('UPDATE accounts SET balance = balance - 100 WHERE id = 1');
$connection->execute('UPDATE accounts SET balance = balance + 100 WHERE id = 2');
$connection->commit();
} catch (\Exception $e) {
$connection->rollBack();
throw $e;
}
Use CakePHP’s query builder for complex queries:
$query = $connection->newQuery()
->select(['name', 'email'])
->from('users')
->where(['active' => true])
->order(['name' => 'ASC'])
->limit(10);
$results = $query->execute()->fetchAll('assoc');
Handle migrations and schema updates:
// Create a table
$connection->execute(<<<SQL
CREATE TABLE IF NOT EXISTS posts (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
)
SQL);
// Describe a table
$schema = $connection->getSchemaCollection()->describe('posts');
Extend Eloquent models to use CakePHP’s connection:
use Illuminate\Database\Eloquent\Model;
use Cake\Database\Connection;
class Post extends Model
{
protected $connection = 'cakephp';
public static function boot()
{
parent::boot();
static::addGlobalScope('active', function (Builder $builder) {
$builder->where('active', true);
});
}
}
Hook into CakePHP’s event system for debugging or logging:
$connection->getEventManager()->on('Model.BeforeSave', function ($event, $entity) {
logger("Saving entity: " . get_class($entity));
});
driver://user:pass@host/database (e.g., mysql://user:pass@localhost/dbname).config/database.php, ensure the driver key is set to 'cakephp' and all required keys (host, username, etc.) are present.$connection->execute('SELECT * FROM `prefix_users`');
->where() instead of Laravel’s ->where() (both work, but CakePHP’s is more flexible).->fetchAll() instead of Laravel’s ->get() for raw results.execute() returns a StatementInterface, not a Laravel Collection. Convert manually if needed:
$results = collect($connection->execute('SELECT * FROM users')->fetchAll('assoc'));
$connection->begin();
$connection->execute('SAVEPOINT level1');
try {
// Inner transaction
$connection->execute('SAVEPOINT level2');
// ...
} catch (\Exception $e) {
$connection->execute('ROLLBACK TO level2');
throw $e;
}
execute() with multi-row inserts for bulk operations:
$data = [
['title' => 'Post 1', 'body' => 'Content 1'],
['title' => 'Post 2', 'body' => 'Content 2'],
];
$connection->execute(
'INSERT INTO posts (title, body) VALUES (:title, :body)',
$data
);
config/app.php:
'Log' => [
'debug' => true,
'write' => 'File',
'paths' => [LOG_DIR],
],
$connection->setQueryLogger(new \Cake\Log\Engine\FileLog([
'path' => storage_path('logs/cakephp_queries.log'),
]));
\Cake\Database\Driver to support unsupported databases.\Cake\Database\Type for custom data types.$connection->getEventManager()->on('Model.Query', function ($event, $query) {
$query->where(['deleted' => false]); // Soft delete filter
});
:param syntax for binding, not ? placeholders.fetchAll() with Laravel’s cursor() or chunk() methods without conversion.How can I help you explore Laravel packages today?