Configuring Laravel/Lumen applications to connect to SQL database sockets

The Laravel/Lumen framework documentation does not explain how to connect an application to a database using UNIX sockets instead of a TCP-based network connection. I recently had to configure the Polr URL shortener (built on the Lumen microframework by Laravel) to connect to Google Cloud SQL with a UNIX socket. Since all of Polr’s configuration takes place in the .env file, and there is no environment variable that’s specific to database sockets, this took some research. I finally found the answer in an obscure StackOverflow response.

Previous TCP connection:

DB_HOST=some-server-name
DB_PORT=3306

Socket-based SQL connection:

DB_HOST=localhost;unix_socket=/cloudsql/cloud-project-name:us-east1:sql-instance-name

This approach will work with any UNIX socket; you just need to give it the absolute path to the socket.

 

Advertisements