Tự học Laravel: (6) Cấu hình Database

Configure the database in Laravel.

RELATED FILE

  • .env
  • config/database.php

.ENV

The. env is a file that collects information to be changed for each environment in the development environment, staging environment, production environment, etc.

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=homestead
DB_USERNAME=homestead
DB_PASSWORD=secret

Write in KEY=VALUE format and change VALUE according to the environment.
If you are using git, add .env to your .gitignore file and unmanage it.

.gitignore

/vendor
/node_modules
.env

CONFIG/DATABASE.PHP

config/database.php is a file to configure the database.

<?php
 
return [
    // ....
    'default' => env('DB_CONNECTION', 'mysql'), 
    'connections' => [
        'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
            'prefix' => '',
        ], 
        '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,
        ], 
        // ....
    ];
];

Define the connection information required for the database type in the connections array. Laravel supports SQLite, MySQL, PostgreSQL, SQL Server.

The connection definition for mysql is env (‘DB_HOST’, ‘127.0.0.1’). This is where you refer to the .env file. Specify KEY as the first argument defined in .env file, and get its VALUE value. The second argument is the default value, which is used when there is no .env file or KEY is not set.

‘default’ => env (‘DB_CONNECTION’, ‘mysql’), in some places specify the database Laravel uses.

If you set DB_CONNECTION=sqlite in the .env file, then you need to create the database.sqlite file manually by commenting out the DB_DATABASE in the .env.

# .env 
DB_CONNECTION=sqlite 
# sqlite
# DB_DATABASE=homestead
touch database/database.sqlite

DB CONNECTION CHECK

Create the default user table by using the artisan migrate command.

$ php artisan migrate

Migration table created successfully.
...

Execute the artisan tinker command to confirm.

$ php artisan tinker

Psy Shell v0.3.4 (PHP 5.6.2 — cli) by Justin Hilema
>>>

Let’s search for User.

>>> App\User::all()->toArray();
=> []
>>>

The inquiry has been completed without error. 
The above example is an example where there is no user, but queries to DB are well done.

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.