As a new web developer I was confused by this question, but today I finally figured it out. Here I want to share with you my notes.
Actually, we have two ways to connect to the database of MySQL in Laravel.
- With Laravel built-in server, run by
php artisan serve
:
- Create a new Laravel project by running it in the terminal in the repository of your choice:
laravel new project_name
. - Once it’s finished, run
cd project_name
. - Suppose you’re using VSCode, run
code .
to open the project folder. - In
.env
, edit as below:
APP_URL=http://127.0.0.1:8000/DB_CONNECTION=mysqlDB_HOST=127.0.0.1DB_PORT=3306DB_DATABASE=project_nameDB_USERNAME=ur_usernameDB_PASSWORD=ur_password
- Go to your terminal and log in to MySQL:
mysql -u ur_username -p
and then enter your password. I suppose you’ve already downloaded mysql globally. - Run
CREATE DATABASE project_name;
thenexit;
. - Find in folder
Config
the filedatabase.php
, and edit in themysql
part as below:
'host' => env('DB_HOST', '127.0.0.1'),'port' => env('DB_PORT', '3306'),'database' => env('DB_DATABASE', 'project_name'),'username' => env('DB_USERNAME', 'ur_username'),'password' => env('DB_PASSWORD', 'ur_password'),
Now run php artisan serve
, try php artisan migrate
to see if the users
table has been migrated to MySQL database, if yes, you’ve connected to the database successfully!
2. Use MAMP, so you can edit the database in phpMyAdmin, and run the project in localhost:
- In the terminal, run
cd /Applications/MAMP/htdocs
. - Create a project in this folder, by running
laravel new project_name
. - In
.env
, edit as below:
APP_URL=http://localhostDB_CONNECTION=mysqlDB_HOST=localhostDB_PORT=3306DB_DATABASE=project_nameDB_USERNAME=rootDB_PASSWORD=ur_passwordDB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock
- In
database.php
, edit as below in the row ofmysql
:
'host' => env('DB_HOST', 'localhost'),'port' => env('DB_PORT', '3306'),'database' => env('DB_DATABASE', 'project_name'),'username' => env('DB_USERNAME', 'root'),'password' => env('DB_PASSWORD', 'ur_password'),'unix_socket' => env('DB_SOCKET', '/Applications/MAMP/tmp/mysql/mysql.sock'),
- Start your MAMP engine, and go to localhost phpMyAdmin to add a database as
project_name
- Test by running
php artisan migrate
, if successful, you will seeusers
table in your phpMyAdmin database. - Now the URL to see your project would be (http://localhost:8888/project_name/public/)
This is my first post on Medium, I hope this article can help people if they get frustrated like me before.