Use Database Connection Strings with Laravel 8

I’ve been doing a lot of database stuff lately, and not much PHP, so when I returned to make my first Laravel project for a while, I had to check the docs to remind myself how some of this works. I noticed that the default approach to database credentials is still to use separate credentials for the host, port, and other variables. I’m using Aiven databases (because I work there and managed databases are great for demo apps as well as real ones!) which supply connection strings, but Laravel supports these too.

For MySQL, the database connection string from Aiven is in the format:


You can remove the configuration for DB_* and instead use the variable DATABASE_URL with the full string.

Pro-tip: Laravel’s built in migrations (I was using Laravel Breeze) expect you to have mysql.sql_require_primary_key disabled, I’m not sure why. It’s default enabled on a lot of systems, including Aiven and Digital Ocean from what I’ve seen so far, so you may need change this setting if your migrations don’t succeed.

For PostgreSQL, the database connection string looks very similar to MySQL but with a pg-specific prefix:


Again, this connection string goes in the variable called DATABASE_URL. For PostgreSQL, you also need to set DB_CONNECTION to pgsql so that Laravel knows to use this connection.

It’s not a big deal to separate the different variables needed for the database connection but especially as a person that spins up a lot of temporary databases to try stuff out and therefore has to update the connections all the time, this was a neat trick that saves me a minute or two every time.

One thought on “Use Database Connection Strings with Laravel 8

  1. Hi,

    Thanks for sharing. But how charset can be set using DATABASE_URL?
    Also, the MySQL connection string can be used directly with PHP PDO?
    Any ideas?

Leave a Reply

Please use [code] and [/code] around any source code you wish to share.

This site uses Akismet to reduce spam. Learn how your comment data is processed.