Connect Your Database in Laravel - Neuroon Networks

Breaking

Wednesday, September 5, 2018

Connect Your Database in Laravel

Laravel makes it very easy to manage your database connections through app/config/database.php and through .env .





Given below is how you have to do it using the app/config/database.php file.

When you first go to that file you will able find a this type of a code (From line number 42)

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    '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,
],



Modify the following property in your app/config/database.php file according to your database settings.

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'Your_Database'),<--- your database name here
    'username' => env('DB_USERNAME', 'root/username'),<--Enter the username here
    'password' => env('DB_PASSWORD', 'password'),<--if there is no password make it empty
    'unix_socket' => env('DB_SOCKET', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
    'engine' => null,
],


Let's do it using .env file. Initially the .env file is .env.sample rename it to .env .  Then you can find a code like below

DB_HOST=YOUR_HOST
DB_DATABASE=YOUR_DATABASE
DB_USERNAME=YOUR_USERNAME
DB_PASSWORD=YOUR_PASSWORD

Modify the following property in your .env file according to your database settings.

DB_HOST=localhost <------- Your host localhost or 127.0.0.1
DB_DATABASE=your_database_name_here  <------- your database name here
DB_USERNAME=root/username  <------Enter the username here
DB_PASSWORD=password <-----  If there is no password make it empty


Once you have configured correctly you will be able to access your database.

To test if you have successfully connected your Laravel project to the database you can run the migration command. Laravel project by default comes with some default table for storing users and their password request. When you run migrate command you it should create the default tables for you in the database.

For that use the command below.

php artisan migrate

Thank you

 

No comments:

Post a Comment