Introduction
Laravel officially supports the following databases:- MySQL / MariaDB
- PostgreSQL
- SQLite
- SQL Server
This page covers the prerequisites of database connections. For practical queries, see Query Builder. For schema management, see Migrations. For initial data population, see Seeding.
Configuration
Database configuration is centralized inconfig/database.php.
You choose the default connection name with default, and define the details of each connection under connections.
.env, at minimum set the following:
DB_CONNECTION=sqlite and the path in DB_DATABASE.
Separating read and write connections
If you want to separate reads (SELECT) and writes (INSERT / UPDATE / DELETE) onto different hosts, configure read and write within the same connection.
sticky to true pins reads after a write to the write connection within the same request.
Pooled PostgreSQL connections
When using a managed PostgreSQL service that provides transaction-mode connection pooling (such as PgBouncer), configure thepooled and direct options.
pooled is enabled, Laravel automatically routes traffic.
If you want to explicitly use the direct connection in application code, add the
::direct suffix to the connection name.
Multiple database connections
You can define multiple connections inconfig/database.php and switch between them with DB::connection().
Executing SQL queries
TheDB facade has dedicated methods for each query type.
Query listening
When you want to track the SQL that is executed, registerDB::listen() in a service provider’s boot() method.
Transactions
To treat multiple updates as a single unit, useDB::transaction().
Laravel automatically rolls back if an exception is thrown.
attempts.
beginTransaction / rollBack / commit.
Next steps
Query Builder
Learn how to safely build queries using your connection configuration.
Migrations
Learn how to version-control the schema of your connected database.
Seeding
Learn how to populate development and test data in a reproducible way.