DEV Community

Funke Olasupo
Funke Olasupo

Posted on • Updated on

How To connect Laravel Application to MySQL Database.


Here is a simple guide on establishing a connection between your database(MySQL) and Laravel application.

Step 1 : Creating the database

This can be done either by a database manager eg phpMyAdmin or the Command Line Interface (CLI).

  • Database Manager(phpMyAdmin)
    Creating a database on phpMyAdmin

  • Command Line Interface(CLI)
    A database can be created with the following command:

Enter fullscreen mode Exit fullscreen mode

P.S: You have to log in to MySQL before you can create a database via any of these methods.

Step 2: Update .env configurations

Laravel default environment file .env contain some common configuration values that differ based on if your application runs locally or on a production server.

P.S: This configuration values are based on my local machine ,
yours may differ, do well to confirm.

Update the .env with the database name you want to connect to,as well as the other environment variables if they differ from the default.

Enter fullscreen mode Exit fullscreen mode

Hurray! πŸŽ‰The laravel application is now properly connected to the database.

Step 3: Migrations(optional)

Laravel migrations simply allows you to easily perform certain actions to the database without going to the database manager (eg. phpMyAdmin). They can also serve as a version control for your database. They create tables, columns as well as modify them etc.

Migrations are found in database/migrations directory.
Laravel application comes default with user migration and it looks like this:
users default migration

It can be executed to the database with the following command:

php artisan migrate
Enter fullscreen mode Exit fullscreen mode

P.S : Refresh your database , it has been updated with users' table and its properties.

users table om database

I wrote an article to explain more on migrations here. You can also visit the laravel documentation here.

You're all set to continue building!😎
Thank you for reading🀝

Top comments (3)

devops007 profile image

Hello Funke, glad to connect with you. I will like to work with you on an open source project.

roxie profile image
Funke Olasupo

Wow, that's amazing . Yes I would love to ! Thank you so much.

Would you like us to move this conversation to Twitter or Linked In ?

Thank you .

bobbyiliev profile image
Bobby Iliev

Great post! Well done! πŸ™Œ