> ## Documentation Index
> Fetch the complete documentation index at: https://kawax.biz/llms.txt
> Use this file to discover all available pages before exploring further.

# Database configuration

> Learn the basics of Laravel database connections, read/write separation, multiple connections, SQL execution, query listening, and transactions.

## Introduction

Laravel officially supports the following databases:

* MySQL / MariaDB
* PostgreSQL
* SQLite
* SQL Server

You can use the same connection configuration whether you're using raw SQL, the query builder, or the Eloquent ORM.

<Info>
  This page covers the prerequisites of database connections. For practical queries, see [Query Builder](/en/query-builder). For schema management, see [Migrations](/en/migrations). For initial data population, see [Seeding](/en/seeding).
</Info>

## Configuration

Database configuration is centralized in `config/database.php`.
You choose the default connection name with `default`, and define the details of each connection under `connections`.

```mermaid theme={null}
flowchart TD
    A[".env"] --> B["config/database.php"]
    B --> C["default connection"]
    B --> D["connections.mysql"]
    B --> E["connections.pgsql"]
    B --> F["connections.sqlite"]
    C --> G["DB facade / Query Builder / Eloquent"]
```

```php theme={null}
// config/database.php
'default' => env('DB_CONNECTION', 'sqlite'),

'connections' => [
    'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'laravel'),
        'username' => env('DB_USERNAME', 'root'),
        'password' => env('DB_PASSWORD', ''),
    ],
],
```

In `.env`, at minimum set the following:

```ini theme={null}
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=app
DB_USERNAME=app_user
DB_PASSWORD=secret
```

When using SQLite, set `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.

```php theme={null}
'mysql' => [
    'driver' => 'mysql',
    'read' => [
        'host' => ['10.0.0.10', '10.0.0.11'],
    ],
    'write' => [
        'host' => ['10.0.0.20'],
    ],
    'sticky' => true,

    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'laravel'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
],
```

Setting `sticky` to `true` pins reads after a write to the write connection within the same request.

<Tip>
  In setups where replicas lag behind, enabling `sticky` reduces the risk of reading stale data immediately after a write.
</Tip>

## Pooled PostgreSQL connections

When using a managed PostgreSQL service that provides transaction-mode connection pooling (such as PgBouncer), configure the `pooled` and `direct` options.

```php theme={null}
'pgsql' => [
    'driver' => 'pgsql',
    // ...
    'pooled' => env('DB_POOLED', false),
    'direct' => array_filter([
        'host' => env('DB_DIRECT_HOST'),
        'port' => env('DB_DIRECT_PORT'),
        'username' => env('DB_DIRECT_USERNAME'),
        'password' => env('DB_DIRECT_PASSWORD'),
        'sslmode' => env('DB_DIRECT_SSLMODE'),
    ]),
],
```

When `pooled` is enabled, Laravel automatically routes traffic.

| Operation                                       | Connection used                                      |
| ----------------------------------------------- | ---------------------------------------------------- |
| Application queries                             | pooled (emulated prepares are enabled automatically) |
| Migrations / `db:wipe` / `db:show` / `db:table` | direct (automatic)                                   |
| `php artisan db`                                | direct (default), switch to pooled with `--pooled`   |

If you want to explicitly use the direct connection in application code, add the `::direct` suffix to the connection name.

```php theme={null}
DB::connection('pgsql::direct')->statement('create extension if not exists "uuid-ossp"');
```

## Multiple database connections

You can define multiple connections in `config/database.php` and switch between them with `DB::connection()`.

```php theme={null}
use Illuminate\Support\Facades\DB;

$users = DB::connection('sqlite')->select('select * from users');
$pdo = DB::connection('pgsql')->getPdo();
```

```mermaid theme={null}
flowchart LR
    A["DB::connection('mysql')"] --> B["Primary DB"]
    C["DB::connection('pgsql')"] --> D["Analytics DB"]
    E["DB::connection('sqlite')"] --> F["Local file DB"]
```

## Executing SQL queries

The `DB` facade has dedicated methods for each query type.

```php theme={null}
use Illuminate\Support\Facades\DB;

$users = DB::select('select * from users where active = ?', [1]);

DB::insert('insert into users (name, email) values (?, ?)', ['Taylor', 'taylor@example.com']);

$affected = DB::update('update users set votes = 100 where name = ?', ['Taylor']);

$deleted = DB::delete('delete from sessions where user_id = ?', [1]);

DB::statement('drop table temporary_imports');
```

<Warning>
  Never concatenate user input directly into SQL strings. Always use binding parameters to prevent SQL injection.
</Warning>

## Query listening

When you want to track the SQL that is executed, register `DB::listen()` in a service provider's `boot()` method.

```php theme={null}
use Illuminate\Database\Events\QueryExecuted;
use Illuminate\Support\Facades\DB;

public function boot(): void
{
    DB::listen(function (QueryExecuted $query) {
        logger()->debug('SQL executed', [
            'sql' => $query->toRawSql(),
            'time_ms' => $query->time,
        ]);
    });
}
```

## Transactions

To treat multiple updates as a single unit, use `DB::transaction()`.
Laravel automatically rolls back if an exception is thrown.

```php theme={null}
use Illuminate\Support\Facades\DB;

DB::transaction(function () {
    DB::update('update users set votes = 1');
    DB::delete('delete from posts where archived = 1');
});
```

If you need deadlock retries, you can specify `attempts`.

```php theme={null}
DB::transaction(function () {
    // ...
}, attempts: 5);
```

If you want manual control, use `beginTransaction` / `rollBack` / `commit`.

```php theme={null}
DB::beginTransaction();

try {
    DB::update('update accounts set balance = balance - 100 where id = ?', [1]);
    DB::update('update accounts set balance = balance + 100 where id = ?', [2]);

    DB::commit();
} catch (\Throwable $e) {
    DB::rollBack();
    throw $e;
}
```

## Next steps

<Card title="Query Builder" icon="table" href="/en/query-builder">
  Learn how to safely build queries using your connection configuration.
</Card>

<Card title="Migrations" icon="hammer" href="/en/migrations">
  Learn how to version-control the schema of your connected database.
</Card>

<Card title="Seeding" icon="seedling" href="/en/seeding">
  Learn how to populate development and test data in a reproducible way.
</Card>


## Related topics

- [Installation](/en/installation.md)
- [MongoDB](/en/mongodb.md)
- [Starter kits](/en/starter-kits.md)
- [Configuration](/en/configuration.md)
- [Session](/en/session.md)
