SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) . DB_HOST set to localhost

farooq picture farooq · Oct 4, 2019 · Viewed 31k times · Source

I know this question may have answers already in stackOverflow . But I have different issue here . I moved the laravel project from localhost to server . Which I have done every steps in server. I can able to view the login page in my server. The problem is, I can't able to connect with my mysql server . my .env file .

APP_NAME=Transport
APP_ENV=local
APP_KEY=base64:mrakeyidharhaikonsdf
APP_DEBUG=true
APP_URL=http://localhost

LOG_CHANNEL=stack

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=transport_db
DB_USERNAME=root
DB_PASSWORD=mypass

I tried to change the host to 127.0.0.1 and also tried to put my server's ip . It didn't helped me. Am I missing something ?

My error :

SQLSTATE[HY000] [1045] Access denied for user 'root'@'localhost' (using password: NO) (SQL: select count(*) as aggregate from users where email = [email protected])

Answer

Salman Zafar picture Salman Zafar · Oct 4, 2019

To be honest while working on laravel 6 i also faced this issue many times and probably was unable to figure out the solution i tried commands like php artisan config:cache and php artisan config:clear but these two commands didn't help.

To come over this issue you have to execute the all the below commands:

php artisan route:cache
php artisan route:clear
php artisan config:cache
php artisan config:clear
php artisan optimize

Note: Make sure in .env you have put db_password and it is not null and also check if your db_password uses any special character always enclose them in ""

Example:

DB_PASSWORD="%123456%"

To debug this issue you can also create a test route and then dump .env variable there to check if they have the correct values or not?

Route::get('/test/env', function () {
    dd(env('DB_DATABASE')); // dump db variable value one by one
});

Hope it helps.

Thanks

Note: Please Make sure to restart your server.