You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Laravel报错SQLSTATE[HY000] [1045]:修改.env后仍无法连接数据库求助

Troubleshooting SQLSTATE[HY000] [1045] Access Denied in Laravel

Hey there, I know how frustrating it is when your Laravel app suddenly throws this access denied error—especially since migrations worked perfectly fine earlier. Let’s walk through targeted fixes that often resolve this issue, even when you’ve already updated your .env and cleared config cache:

  • Verify your app is actually using your updated config values
    Sometimes even after editing .env and running php artisan config:clear, there might be a lingering mismatch. To confirm what your app is loading, add a quick debug check:

    // Drop this into a test route or temporary controller method
    dd(config('database.connections.mysql'));
    

    Visit that route in your browser and check the username field. If it still shows homestead instead of your custom user, double-check your .env for typos—common mistakes include misspelled variables like DB_USER instead of DB_USERNAME, or extra spaces after values (e.g., DB_PASSWORD= mypassword with a leading space).

  • Check your MySQL user’s host permissions
    Just because migrations worked before doesn’t mean the user’s access hasn’t changed. Log into your MySQL terminal and run these commands:

    // List all users and their allowed hosts
    SELECT user, host FROM mysql.user;
    

    Make sure your custom database user exists with host set to localhost (not % or another IP). If it’s missing, create it with full permissions for your database:

    GRANT ALL PRIVILEGES ON your_database_name.* TO 'your_custom_user'@'localhost';
    FLUSH PRIVILEGES;
    
  • Fix syntax issues in your .env file
    If your password contains special characters (like !, @, or spaces), wrap it in double quotes to ensure it’s parsed correctly:

    DB_PASSWORD="my!super$ecurepass"
    

    Also, double-check for trailing commas or missing equals signs in any of your database variables.

  • Clear all caches, not just config
    Sometimes other caches can interfere. Run these commands in sequence:

    php artisan config:clear
    php artisan cache:clear
    php artisan route:clear
    php artisan view:clear
    

    Note: If you ever ran php artisan config:cache in the past, this command compiles your config into a single file—any subsequent .env changes won’t take effect until you run config:clear or re-run config:cache with updated values.

  • Restart your MySQL service
    Rarely, a MySQL service glitch can cause permission issues even when everything looks correct. Restart the service:

    • On Linux: sudo service mysql restart
    • On Windows: Open Services, find MySQL, and click "Restart"

内容的提问来源于stack exchange,提问作者Zouzou 86

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 09:57:45