How To Connect Mysql With Laravel ?

In Laravel Development, the Connection of Laravel with Mysql is a bit easy but lengthy. Let’s take a took to the process :

Step 1: Open Phpmyadmin or any DBMS tool you are using.

Step 2: create a database. let’s say laraveldb. By query, you can create DB as
CREATE DATABASE laraveldb


Step 3: Setting database connection parameters for Laravel.

    • Open config/database.php

    • See the following lines of code.

‘mysql’ => [

‘driver’ => ‘mysql’,

‘host’ => env(‘DB_HOST’, ‘localhost’),

‘port’ => env(‘DB_PORT’, ’80’),

‘database’ => env(‘DB_DATABASE’, ‘forge’),

‘username’ => env(‘DB_USERNAME’, ‘forge’),

‘password’ => env(‘DB_PASSWORD’, ”),

‘unix_socket’ => env(‘DB_SOCKET’, ”),

‘charset’ => ‘utf8mb4’,

‘collation’ => ‘utf8mb4_unicode_ci’,

‘prefix’ => ”,

‘strict’ => true,

‘engine’ => null,

],

  • Change the colored code lines as per your database.

                 ‘port’ => env(‘DB_PORT’, ’80’), //Change this if ur port is different than 80

                 ‘database’ => env(‘DB_DATABASE’, ‘laraveldb’), //database name

                 ‘username’ => env(‘DB_USERNAME’, ‘root’), // mysql db username

                 ‘password’ => env(‘DB_PASSWORD’, ”), //mysql db password.

Step 4: you may face error like Access denied for user ‘homestead’@’ localhost’ (using password: YES). You will get the above message even if you have set the correct parameters in database.php  because the artisan command-line tool uses the database connection parameters specified in .env file.

Step 5: Open .env file & locate the following lines of code.

DB_DATABASE=homestead
DB_USERNAME= homestead
DB_PASSWORD=secret
update the above by the following code
DB_DATABASE=laraveldb
DB_USERNAME= root
DB_PASSWORD=

Step 6:
The database, username and password must match with your MySQL on your system.

Now your database connection is ready.

Related Posts