Laravel 5.4 sqlstate[hy000] [2002] connection refused

When I was building a simple web app, I had a problem with Laravel 5.4 sqlstate[hy000] [2002] connection refused. It took me some time to figure it out and here is my solution for Laravel 5.4 sqlstate[hy000] [2002] connection refused.

1. Check your .env file

The error says sqlstate[hy000] [2002] connection refused, so it means there are some problems with the database. The .env file under the root folder is the file which you should check first.

Make sure that the information in this section is correct based on what you set up. For example, if I have a database called larapress and my username for the database is root and so does my password. Then the solution for sqlstate[hy000] [2002] connection refused is to enter the information accordingly:

 

2. Check the DB_PORT

If you are using MAMP or WAMP, the portal for your database has been set to 8889 by default instead of 3306. So you have to change the DB_PORT in your .env to 8889 or change your MAMP or WAMP port to 3306. In my case, I changed the DB_PORT in .env file to 8889 in order to match MAMP setting.

 

3. Change DB_HOST to localhost

I saw solutions in some forum saying to change the DB_HOST from 127.0.0.1 to localhost can solve the problem. Well, in my case, this didn’t help, but you are welcome to have a try.

 

4. Restart your local server! Very important.

After you made any changes in the .env file. You should restart your local server by closing your MAMP and closing every terminal tabs. Trust me, I should have restarted my whole server before I wasted some much time.

Then try to restart the MAMP and boost your Laravel application by re-typing php artisan serve in your app folder.

 

5. Clean the cache if it still doesn’t work.

In your app folder, type php artisan config:clear in the terminal and it should clean your config cache. Try to restart your MAMP and Laravel after this to see if it solves the problem.

Leave a Reply

Your email address will not be published. Required fields are marked *