Laravel数据库连接失败排查:配置正确但报1045权限错误
It looks like Laravel is still clinging to the default 'homestead' credentials even though you’ve updated your .env file to use 'root'. Let’s walk through the most common fixes to get this sorted:
1. Clear Config and Cache
Laravel caches configuration values for speed, so if you’ve tweaked your .env recently, those changes might not be active yet. Run these commands in your project root to wipe the cache:
php artisan config:clear php artisan cache:clear
This forces Laravel to read your fresh .env values instead of relying on stale cached settings.
2. Fix .env File Formatting
Looking at your snippet, all your DB variables are crammed onto a single line—each environment variable needs its own line for Laravel to parse them correctly. Your .env should look like this:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=chat DB_USERNAME=root DB_PASSWORD=root
If they’re all on one line, Laravel won’t recognize your custom username/password and falls back to the default 'homestead' from the config file.
3. Verify database.php Config
Double-check your config/database.php file to make sure the MySQL connection is pulling values from your .env. The 'mysql' array should have these lines:
'mysql' => [ 'driver' => 'mysql', 'host' => env('DB_HOST', '127.0.0.1'), 'port' => env('DB_PORT', '3306'), 'database' => env('DB_DATABASE', 'forge'), 'username' => env('DB_USERNAME', 'homestead'), 'password' => env('DB_PASSWORD', 'secret'), // ... other settings ],
Ensure the 'username' and 'password' fields use env('DB_USERNAME', ...) instead of being hardcoded to 'homestead'. If they’re hardcoded, Laravel will ignore your .env values entirely.
4. Test Credentials Directly with MySQL
Let’s rule out MySQL setup issues first. Test your credentials using the MySQL command line:
mysql -u root -p root -h 127.0.0.1 -P 3306 chat
If this fails:
- The 'chat' database might not exist (create it with
CREATE DATABASE chat;in MySQL). - The root user might not have permission to connect from 127.0.0.1. Fix that with:
GRANT ALL PRIVILEGES ON chat.* TO 'root'@'127.0.0.1' IDENTIFIED BY 'root'; FLUSH PRIVILEGES;
5. Check MySQL Listening Address
Some MySQL installations default to using a Unix socket instead of TCP/IP. If you’re stuck with 127.0.0.1, try changing DB_HOST in .env to localhost (this uses the socket connection instead of TCP).
After trying these steps, restart your Laravel server (if using php artisan serve) and test the connection again.
内容的提问来源于stack exchange,提问作者Lyes

