0

I'm having issues connecting to a docker instance of MySQL through Laravel. I've found that by using Tinker, I can connect successfully to the database. e.g, with Tinker, if I run

DB::select("select * from users;");

I'm able to get results. However, if I make a route

Route::post('/sql', function(Request $request){
return DB::select('select * from appointments;')->get();
});

and hit it through PostMan, I get back

    "message": "SQLSTATE[HY000] [2002] Connection refused (SQL: select * from `users` where `users`.`id` = 1 limit 1)",

I currently have the .env file set with

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=test_project
DB_USERNAME=root
DB_PASSWORD=password

I've read that many people have trouble with using 127.0.0.1, but I've found that when I switch the DB_HOST to localhost, tinker doesn't even successfully connect. Instead, I get

Illuminate/Database/QueryException with message 'SQLSTATE[HY000] [2002] No such file or directory (SQL: select * from users;)'

I've already tried php artisan route:clear php artisan config:clear php artisan cache:clear

But I cannot get this to work. Any help or insight is greatly appreciated!

blake
  • 83
  • 7
  • Please check the trouble-shooting hints that are available for the error message. There can be many reasons why the connection is not possible. To troubleshoot, a hand-made connection script with PDO alone and testing the configuration values for the connection can also be helpful to get things out of the way fast. From the information in the question alone it is merely guesswork which leads to extended discussions - for these please see the linked duplicates. – hakre Jul 05 '21 at 21:16
  • 1
    I finally figured it out. In the .env file, instead of using 127.0.0.1 OR localhost, instead, I had to use the name of my mysql docker container. DB_HOST=DB_HOST=test_project_mysql_1 – blake Jul 05 '21 at 22:01
  • you should have searched for the error message plus laravel and docker on site and you would have found it in no time. perhaps tinker runs inside docker and has the environment parameter properly set therein? – hakre Jul 05 '21 at 22:38
  • I searched for hours for posts containing my error message plus laravel and docker, and found nothing. That could be the case. – blake Jul 05 '21 at 23:02
  • when I saw your question I went to duck duck go, put in `php laravel site:stackoverflow.com`. picked the second best hit with the most upvotes, scanned the answers and decided its the duplicate. just in case if you wonder how I did it. - knowing that your is with docker had made the scanning of the answers _easier_. and I also check for the date of question and answer, most often the older ones are more valuable. like a good wine. – hakre Jul 05 '21 at 23:04

0 Answers0