Laravel beginners running into database connection errors when executing 'php artisan migrate'.
- ✓PHP 8.2+ installed with pdo_mysql extension
- ✓MySQL server running locally via XAMPP, Laragon, or standalone MySQL
🚀 What You Will Learn & Build
- ▸Configuring config/database.php and .env for MySQL
- ▸Understanding DB_HOST 127.0.0.1 vs localhost in PHP sockets
- ▸Resolving SQLSTATE[HY000] [2002] Connection refused
- ▸Resolving SQLSTATE[HY000] [1045] Access denied for user
1. The Correct .env Configuration for MySQL
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=my_laravel_app
DB_USERNAME=root
DB_PASSWORD=
# Tip: If using XAMPP on Windows, DB_PASSWORD is empty by default.
# If using Laragon or Docker, check your custom root password.2. Fixing SQLSTATE[HY000] [2002] Connection Refused
3. Fixing SQLSTATE[HY000] [1045] Access Denied for User
-- Open MySQL prompt and grant privileges
ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'YourNewPassword';
FLUSH PRIVILEGES;✨ Expected Output & Verification
Running 'php artisan migrate' creates default tables (users, password_reset_tokens, failed_jobs, personal_access_tokens) successfully with: INFO Preparing database. INFO Running migrations. 2014_10_12_000000_create_users_table ......... DONE
🧪 How to Test the Implementation
- 1Run `php artisan db:show` in terminal to view table list and connection health
- 2Run `php artisan migrate:status` to ensure database connection is active
⚠️ Common Errors & How to Fix Them
Root Cause: Database does not exist in MySQL yet.
Fix: Create database in phpMyAdmin: CREATE DATABASE my_laravel_app CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
🛡️ Security Considerations & Best Practices
- !Never use the 'root' user in production. Create a dedicated database user with restricted permissions for the specific database only.
❓ Frequently Asked Questions (FAQ)
Laravel caches configuration files. Run 'php artisan config:clear' whenever you change database credentials in .env.
📌 Summary of Key Takeaways
- ✓Use 127.0.0.1 instead of localhost for DB_HOST.
- ✓Clear config cache with 'php artisan config:clear' after editing .env.
Official References & Further Reading
- 🔗Laravel Database Configuration Docs— Official guide on database connections and read/write replicas.
Written by Manoj Neupane
AuthorSoftware developer and programming instructor, Nepal
Building software systems and SaaS platforms with Laravel, Next.js, and Node.js. Passionate about helping students and developers in Nepal master practical, real-world development skills.