Configuring Heroku Postgres with Laravel
This blog post was originally published a little while ago. Please consider that it may no longer be relevant or even accurate.
Today Laravel shipped v5.8.15 which comes with a great improvement for configuring your database connections - especially on platforms like Heroku. You can now provide a fully-qualified database URL for the connection rather than host, username, password, and database separately.
Heroku will use this fully-qualified URL for it's first-party Postgres and Redis add-ons. For example your application will receive an environment variable like DATABASE_URL=postgres://username:password@host:port/database
. This contains everything needed to connect to that database.
Previously you would need to use parse_url
to break down this environment variable and pass each component to the database configuration.
But as of this latest version of Laravel you can just provide the url
key with the database URL and it will work out the rest - the driver, host, port, database, username & password.
Note that here I've used DATABASE_URL
instead of something like DB_URL
(which would better match Laravel's naming convention) as that's what Heroku gives you. It's likely easier to just use DATABASE_URL
in local development so you can just push to production & go.
For more information, view PR #28308 from @mathieutu.