Twitter

How To Connect A Laravel App To A MySQL Database

by Adam Patel

MacBook Pro with images of computer language codes

If you’ve been following my series of articles on setting up a laravel app on shared hosting, at this point, you’ve installed Laravel Breeze for user registration and authentication. Of course, without connection to a MySQL database, this isn’t going to work. So that’s our focus for this post.

This step is relatively straightforward if you know how.

Step #1 – Create A MySQL database via your cPanel

Click on MySQL databases and create a new database. It’s that simple. You don’t have to make any tables or anything – laravel will do that for you. The database just needs to exist so that the app an connect to it.

Step #2 – Setup The Database Connection

In the root folder of your Laravel app, there is a hidden file that is probably currently called .env.example. This is the only file you need edit in order to connect to the database. This file creates constants which will then be used in config/database.php. But you don’t need to touch that file in order to get this working.

Within your .env.example file, you’ll need to edit lines 10 to 15 as follows:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=sharedhostinguser_databasename
DB_USERNAME=sharedhostinguser_MySQLusername
DB_PASSWORD='password between single quotes'

The first three lines remain the same.

DB_DATABASE is the database name. When you create databases on sharedhosting, they take the form of your cpanel username followed by an underscore, followed by whatever name you give the database.

The username follows the same pattern. If this is the first time ever that you’re setting up a MySQL database, you may also need to create a user and then attribute the user to the database.

Your password goes between single quotes.

That’s it. Save the changes.

Step #3 – Rename .env.example as .env

Finally, you need to rename the file so that the app can recognise it and use the settings you’ve just set.

Step # 4 – Test the connection by performing a database migration

The easiest way to know whether your database is connected is to perform a database migration.

php artisan migrate

If you don’t get some green lines of text telling you that various tables have been created, you might get an error telling you that a key was too long. If so, don’t worry, I’ve got you covered in this post. If it worked successfully, move right on to this article.

Copyright 2021. All Rights Reserved. Adam Patel