DEV Community

Funke Olasupo
Funke Olasupo

Posted on • Updated on

How To connect Laravel Application to MySQL Database.

Introduction

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:

CREATE DATABASE db_name;
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.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test
DB_USERNAME=root
DB_PASSWORD=
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)

Collapse
 
devops007 profile image
TalkSpot.ng

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

Collapse
 
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 ?

linkedin.com/in/olasupofunke/

twitter.com/OlasupoFunke

Thank you .

Collapse
 
bobbyiliev profile image
Bobby Iliev

Great post! Well done! ๐Ÿ™Œ