How to configure database in Laravel

Share:
Configuring Database in laravel 5.4. Laravel Provides simple steps to connect with various Databases. Currently Laravel supports four databases :-
  • MySQL
  • Postgres
  • SQLite
  • SQL Server
Laravel database configuration file is located as config/database.php .Here you can define all of your database connections. Below are the steps to configure database in Laravel.

MySQL Database Configuration

In database.php you have connections array, find below code and modify host,database, username, passwords keys values to yours. If your server is not using mysql default port i.e 3306 , then please change port too.

'mysql' => [
            'driver' => 'mysql',
            'host' => env('DB_HOST', 'your_host'),
            'port' => env('DB_PORT', '3306'),
            'database' => env('DB_DATABASE', 'your_database'),
            'username' => env('DB_USERNAME', 'your_mysql_username'),
            'password' => env('DB_PASSWORD', 'your_mysql_password'),
            'unix_socket' => env('DB_SOCKET', ''),
            'charset' => 'utf8mb4',
            'collation' => 'utf8mb4_unicode_ci',
            'prefix' => '',
            'strict' => true,
            'engine' => null,
        ]

SQL Server Database Configuration

Laravel support SQL server however, you will need to add below connection configuration in connections array of config/database.php file.Update host,database, username, passwords keys values to yours

'sqlsrv' => [
    'driver' => 'sqlsrv',
    'host' => env('DB_HOST', 'your_host'),
    'database' => env('DB_DATABASE', 'your_database'),
    'username' => env('DB_USERNAME', 'your_useername'),
    'password' => env('DB_PASSWORD', 'your_password'),
    'charset' => 'utf8',
    'prefix' => '',
],

Configuring Postgres on Laravel

To configure Postgres database modify host,database, username, passwords keys values to yours

'pgsql' => [
            'driver' => 'pgsql',
            'host' => env('DB_HOST', 'your_host'),
            'database' => env('DB_DATABASE', 'your_database'),
            'username' => env('DB_USERNAME', 'your_useername'),
            'password' => env('DB_PASSWORD', 'your_password'),
            'charset' => 'utf8',
            'prefix' => '',
            'schema' => 'public',
            'sslmode' => 'prefer',
        ]

Configuring SQLite on Laravel

After creating a new SQLite database using below command

touch database/database.sqlite

DB_CONNECTION=sqlite DB_DATABASE=/absolute/path/to/database.sqlite

'sqlite' => [
            'driver' => 'sqlite',
            'database' => env('DB_DATABASE', database_path('database.sqlite')),
]

Configuring your default database in Laravel

'default' => env('DB_CONNECTION', 'mysql');

No comments