Database: Getting Started
NaluzPHP’s database layer has three parts that you can use independently:
Connection: a PDO wrapper with prepared statements, transactions and query listeners.- Query builder:
Naluz\Database\Query\Builder, returns collections of plain arrays. See Query builder. - ORM:
Naluz\Database\Orm\Model, returns models, built on top of the query builder. See Models.
$manager = app(Naluz\Database\DatabaseManager::class);$db = $manager->connection(); // the default connection$db->table('users')->where('active', true)->get(); // query builder, no models involvedUser::where('active', true)->get(); // ORMConfiguration
Section titled “Configuration”Connections are defined in config/database.php. Choose the default with DB_CONNECTION:
DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=myappDB_USERNAME=myappDB_PASSWORD=secret| Driver | DB_CONNECTION |
Default for |
|---|---|---|
| SQLite | sqlite |
storage/database.sqlite (the default connection) |
| MySQL / MariaDB | mysql |
port 3306 |
| PostgreSQL | pgsql |
port 5432 |
| SQL Server / Azure SQL | sqlsrv |
port 1433 |
See Database drivers for driver-specific notes.
More than one connection
Section titled “More than one connection”Add connections to config/database.php and use them by name:
$manager->connection('reporting')->table('events')->get();
class Event extends Model{ protected ?string $connection = 'reporting';}Transactions
Section titled “Transactions”$db->transaction(function () use ($db) { $db->table('accounts')->where('id', 1)->decrement('balance', 100); $db->table('accounts')->where('id', 2)->increment('balance', 100);}); // commits, or rolls back if the closure throwsNested transaction() calls use savepoints.
Debugging queries
Section titled “Debugging queries”$sql = $db->table('users')->where('id', 5)->toSql(); // 'SELECT * FROM "users" WHERE "id" = ?'$bindings = $db->table('users')->where('id', 5)->getBindings();$db->listen(fn (string $sql) => logger($sql)); // every statement executedRead replicas
Section titled “Read replicas”Send reads to replicas and writes to a primary with a few environment variables. See Read/write connections.
Other stores
Section titled “Other stores”For document data, see NoSQL. To cache query results automatically, see Model caching.