Connecting mysql database with laravel app in heroku

Shantu Chandra Das
2 min readOct 30, 2018

--

heroku

My last post was about how to host your laravel application in heroku. If you are new to this blog then this is highly recommended to checkout my previous blog.

If you already know how to deploy your laravel app then just follow this tutorial to connect with database.

(Step-1) Log in to your heroku app

To log in use command $heroku login Enter your email and password.

$ heroku login
heroku: Enter your login credentials
Email: your_mail@example.com
Password:*****

(Step-2) Adding ClearDB to your app

There is a heroku add-on called ClearDB that provides mysql heroku support to your laravel app. To create your ClearDB database just hit this command.

heroku addons:create cleardb:ignite

This will create a free database. To show your database information use command line.

heroku config | grep CLEARDB_DATABASE_URLCLEARDB_DATABASE_URL:mysql://your_user_name:your_password@your_host/heroku_12bec7eed2bae54?reconnect=true

This command will give you something like that, don’t worry to write it down because this information will be passed on as an environment variable. If you want connect with mysql workbench or mysql pro, you can use this information to connect your database. Just use your information properly and use 3306 as your port number.

(STEP-3) Set up database

Go to your laravel project and navigate to app\config\database.php and paste this lines of code before returning any database configuration.

$url = parse_url(getenv("CLEARDB_DATABASE_URL"));

$host = $url["host"];
$username = $url["user"];
$password = $url["pass"];
$database = substr($url["path"], 1);

create a connection like this

'your_heroku_mysql_connection' => array(
'driver' => 'mysql',
'host' => $host,
'database' => $database,
'username' => $username,
'password' => $password,
'charset' => 'utf8',
'collation' => 'utf8_unicode_ci',
'prefix' => '',
),

and, use your_heroku_mysql_connection as your default database connections

'default' => env('DB_CONNECTION', 'your_heroku_mysql_connection'),

Your, database config should be like this

That’s it.

Thanks for taking your time to read, I do hope the article has helped you! If you liked this article don’t forget to clap.

Happy coding ✌

--

--