0
0
Laravelframework~5 mins

Database configuration in Laravel

Choose your learning style9 modes available
Introduction

Database configuration tells Laravel how to connect to your database. It helps your app save and get data easily.

When setting up a new Laravel project to connect to a database.
When changing the database server or credentials.
When switching between different database types like MySQL or SQLite.
When configuring multiple database connections for different parts of your app.
Syntax
Laravel
/* In the .env file */
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_username
DB_PASSWORD=your_password

The .env file holds your database settings securely.

Laravel reads these settings automatically to connect to the database.

Examples
Example for using SQLite with a file path.
Laravel
DB_CONNECTION=sqlite
DB_DATABASE=/absolute/path/to/database.sqlite
Example for PostgreSQL database connection.
Laravel
DB_CONNECTION=pgsql
DB_HOST=127.0.0.1
DB_PORT=5432
DB_DATABASE=my_pg_db
DB_USERNAME=pg_user
DB_PASSWORD=secret
Example for MySQL with a remote host.
Laravel
DB_CONNECTION=mysql
DB_HOST=192.168.1.10
DB_PORT=3306
DB_DATABASE=shop
DB_USERNAME=shop_user
DB_PASSWORD=shop_pass
Sample Program

This Laravel route fetches all users from the database and returns them as JSON. It uses the database configuration from the .env file to connect.

Laravel
<?php

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Route;

Route::get('/db-test', function () {
    $users = DB::table('users')->get();
    return response()->json($users);
});
OutputSuccess
Important Notes

Always keep your .env file secret and never share it publicly.

After changing .env settings, run php artisan config:cache to refresh config.

Use Laravel's built-in DB facade or Eloquent ORM to interact with the database easily.

Summary

Database configuration tells Laravel how to connect to your database.

Settings are stored in the .env file for security and flexibility.

Use the DB facade or Eloquent to work with your database after configuring it.