Laravel Database Configuration

Lesson 21 of 50 - Learn how to connect Laravel with MySQL and other databases.

42%
1. What Is Database Configuration?

Database configuration means connecting your Laravel application to a database so it can store, retrieve, update, and delete information.

Laravel supports several database systems, including:

  • MySQL
  • PostgreSQL
  • SQLite
  • SQL Server

Laravel uses database settings from the .env file and the config/database.php configuration file.

2. Create a MySQL Database

Before connecting Laravel to MySQL, create a database. You can use phpMyAdmin, MySQL Workbench, or the MySQL command line.

Example SQL command:

CREATE DATABASE laravel_app;

This creates a database named laravel_app.

You can use a different database name for your project. Make sure the MySQL user configured for Laravel has permission to access the database.

3. Configure the .env File

Open the .env file in the root directory of your Laravel project.

Configure the MySQL connection:

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=laravel_app
DB_USERNAME=root
DB_PASSWORD=

Explanation:

  • DB_CONNECTION specifies the database driver.
  • DB_HOST specifies the database server address.
  • DB_PORT specifies the database server port.
  • DB_DATABASE specifies the database name.
  • DB_USERNAME specifies the database username.
  • DB_PASSWORD specifies the database password.

These values are examples for a local development environment. Use your actual database credentials. Never publish database passwords in public repositories.

4. Understand config/database.php

The config/database.php file defines the database connections available to your application.

A simplified MySQL connection example is:

'mysql' => [
    'driver' => 'mysql',
    'url' => env('DB_URL'),
    'host' => env('DB_HOST', '127.0.0.1'),
    'port' => env('DB_PORT', '3306'),
    'database' => env('DB_DATABASE', 'laravel_app'),
    'username' => env('DB_USERNAME', 'root'),
    'password' => env('DB_PASSWORD', ''),
    'charset' => 'utf8mb4',
    'collation' => 'utf8mb4_unicode_ci',
    'prefix' => '',
    'strict' => true,
],

This is an illustrative connection array, not a complete replacement for your configuration file. Keep the other existing settings supplied by your Laravel version.

Laravel reads environment variables to build the connection configuration.

5. Test the Database Connection

You can test the database connection from a route using Laravel's database facade.

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

Route::get('/database-test', function () {

    try {
        DB::connection()->getPdo();

        return 'Database connected successfully!';
    } catch (\Throwable $e) {
        report($e);

        return response(
            'Database connection failed. Check your configuration.',
            500
        );
    }
});

Add the code to routes/web.php and visit /database-test in your browser.

If the connection fails, check the database server, credentials, database name, and configured port. Review your Laravel logs for the detailed error rather than displaying database exceptions to visitors.

Remove this diagnostic route after testing or restrict access to it in a real application.

6. Use the Database Facade

Laravel provides the DB facade to execute database queries using the query builder.

Example: retrieve all students from a table.

use Illuminate\Support\Facades\DB;

Route::get('/students', function () {

    $students = DB::table('students')->get();

    return response()->json($students);
});

This example assumes that a students table already exists.

Example: insert a student record.

DB::table('students')->insert([
    'name' => 'Rahul Kumar',
    'email' => 'rahul@example.com',
]);

The insert example assumes the table contains compatible name and email columns. Add other required fields if your schema needs them.

7. Run Database Commands Using Artisan

Laravel provides useful Artisan commands for database operations.

Check available Artisan commands:

php artisan list

Run pending migrations:

php artisan migrate

Check migration status:

php artisan migrate:status

Clear cached configuration:

php artisan config:clear

If you change database settings while configuration is cached, clear or rebuild the configuration cache as appropriate.

Before running destructive database commands, back up important data and verify which database connection your application is using.

8. Common Database Connection Errors

Here are common problems and their solutions:

Error or Problem Possible Solution
Unknown database Create the database or correct DB_DATABASE.
Access denied Check the username, password, and database permissions.
Connection refused Check whether the database server is running and the host and port are correct.
Table does not exist Check the table name and run the required migrations.
Old settings still used Check configuration caching and clear it if necessary.

Always check your Laravel logs when troubleshooting. Avoid exposing database credentials or detailed exceptions in public error messages.

9. Practical Assignment

Complete the following tasks:

  1. Create a MySQL database named laravel_app.
  2. Configure the database credentials in your .env file.
  3. Understand the MySQL connection settings in config/database.php.
  4. Create a route that tests the database connection.
  5. Use DB::table() to retrieve records from an existing table.
  6. Run php artisan migrate and check migration status.
  7. Practice identifying common database connection errors.

Make sure you are connected to your intended development database before running migrations or inserting records.

Quick Quiz

1. Which file commonly stores Laravel environment variables?




2. Which facade is commonly used to execute query builder operations?




3. Which Artisan command runs pending migrations?