Lesson 21 of 50 - Learn how to connect Laravel with MySQL and other databases.
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:
Laravel uses database settings from the
.env file and the
config/database.php configuration file.
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.
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.
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.
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.
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.
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.
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.
Complete the following tasks:
laravel_app..env file.config/database.php.DB::table() to retrieve records from an existing table.php artisan migrate and check migration status.Make sure you are connected to your intended development database before running migrations or inserting records.
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?