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

Configure the database in Laravel.


  • .env
  • config/database.php


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


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.




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

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', ''),
            '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’, ‘’). 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 
# sqlite
# DB_DATABASE=homestead
touch database/database.sqlite


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.