Laravel 7数据库连接失败报SQLSTATE[HY000][1698]错误,如何解决?
Hey there, let's work through this database connection issue you're hitting in Laravel 7. That error is super common with newer MySQL versions, and I bet I know exactly what's going on—especially since your Laravel 5.4 setup works fine.
What's Causing This?
Starting with MySQL 5.7, the default root user uses the auth_socket authentication plugin instead of password-based authentication. This means MySQL checks if your system user matches the database user (so you can only log in as root via sudo mysql), rather than accepting a password.
Your Laravel 5.4 project is likely running against an older MySQL instance where root was configured with password authentication, which is why it connects without issues.
Solution 1: Update the root User's Authentication Method
If you want to keep using the root user for your Laravel 7 project, follow these steps:
- Log into MySQL using system root privileges:
sudo mysql -u root - Switch to the
mysqldatabase (where user accounts are stored):USE mysql; - Update the
rootuser to use password authentication (we'll use an empty password to match your.env):
Note: If you'd prefer to set a secure password instead of leaving it blank, replace the empty quotes with your desired password and update yourALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY '';.envfile accordingly. - Flush MySQL privileges to apply the changes:
FLUSH PRIVILEGES; - Exit MySQL, then clear Laravel's config cache again (just to be safe) and restart your server:
php artisan config:clear php artisan serve
Solution 2: Create a Dedicated Database User (Recommended)
Using root for your application isn't the most secure practice. Instead, create a separate user for Laravel:
- Log into MySQL with
sudo mysql -u rootas before. - Create a new user (replace
your_usernameandyour_passwordwith your preferred credentials):CREATE USER 'your_username'@'localhost' IDENTIFIED BY 'your_password'; - Grant full access to your
amazon_servicesdatabase:GRANT ALL PRIVILEGES ON amazon_services.* TO 'your_username'@'localhost'; - Flush privileges:
FLUSH PRIVILEGES; - Update your
.envfile to use this new user:DB_USERNAME=your_username DB_PASSWORD=your_password - Clear config cache and restart the server:
php artisan config:clear php artisan serve
Either of these methods should fix the access denied error. The second option is better for security, but both will get your Laravel 7 project connected to the database properly.
内容的提问来源于stack exchange,提问作者manikandan

