Laravel: Connect to Neon serveless postgresql database

Carlos Costa

A serverless database is a cloud-based system that dynamically manages the allocation of machine resources.

The connection to a serverless database is the same as a regular database, but the connection string is different.

DB_CONNECTION=pgsql
DB_HOST=(database-host)
DB_PORT=5432
DB_DATABASE=(database-name)
DB_USERNAME=(database-user)
DB_PASSWORD=endpoint=(database-id);(database-password)
DB_SSLMODE=require

The database host looks like: ep-foo-bar-00000.us-east-2.aws.neon.tech and the id is the first item of the host name, in this case ep-foo-bar-00000.

In the config/database.php file, we need add sslmode to psql connection and expose to env config.

'pgsql' => [
    'driver' => 'pgsql',
    'url' => env('DATABASE_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '5432'),
    'database' => env('DB_DATABASE', 'forge'),
    'username' => env('DB_USERNAME', 'forge'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8',
    'prefix' => '',
    'prefix_indexes' => true,
    'search_path' => 'public',
    'sslmode' => env('DB_SSLMODE', 'prefer'),
],