442

I believe that I've successfully deployed my (very basic) site to fortrabbit, but as soon as I connect to SSH to run some commands (such as php artisan migrate or php artisan db:seed) I get an error message:

[PDOException]
SQLSTATE[HY000] [2002] No such file or directory

At some point the migration must have worked, because my tables are there - but this doesn't explain why it isn't working for me now.

Daniel Hollands
  • 6,281
  • 4
  • 24
  • 42
  • Possible duplicate of [PHP - MySQL connection not working: 2002 No such file or directory](http://stackoverflow.com/questions/1676688/php-mysql-connection-not-working-2002-no-such-file-or-directory) – kenorb Nov 13 '15 at 12:20
  • 1
    sometimes it just because you havent installed mysql yet – Hassan Gilak Apr 22 '16 at 13:28
  • For me it was setting `'host' => 'mysql',` in `config/database.php` and commenting `unix_socket` parameter. – temo Dec 29 '21 at 13:44

37 Answers37

860

One of simplest reasons for this error is that a MySQL server is not running. So verify that first. In case it's up, proceed to other recommendations:

Laravel 4: Change "host" in the app/config/database.php file from "localhost" to "127.0.0.1"

Laravel 5+: Change "DB_HOST" in the .env file from "localhost" to "127.0.0.1"

I had the exact same problem. None of the above solutions worked for me. I solved the problem by changing the "host" in the /app/config/database.php file from "localhost" to "127.0.0.1".

Not sure why "localhost" doesn't work by default but I found this answer in a similar question solved in a symfony2 post. https://stackoverflow.com/a/9251924

Update: Some people have asked as to why this fix works so I have done a little bit of research into the topic. It seems as though they use different connection types as explained in this post https://stackoverflow.com/a/9715164

The issue that arose here is that "localhost" uses a UNIX socket and can not find the database in the standard directory. However "127.0.0.1" uses TCP (Transmission Control Protocol), which essentially means it runs through the "local internet" on your computer being much more reliable than the UNIX socket in this case.

Benjamin Loison
  • 3,782
  • 4
  • 16
  • 33
stuyam
  • 9,561
  • 2
  • 21
  • 40
  • 3
    strange that it was the solution for me too, but i am able to connect from the command line with mysql --host=localhost - that works, but not from PDO. – John Jun 23 '14 at 17:24
  • 65
    I would love to know WHY `localhost` doesn't work and `127.0.0.1` does?? – Justin Oct 18 '14 at 02:35
  • 6
    This worked for me on a MAMP system running a php file on the command line (terminal). It worked as a webpage, but not as a command line file until I changed localhost to '127.0.0.1' – Samuel Fullman Jan 08 '15 at 11:57
  • Also see @Marlow 's answer where he adds a `port` to the config array. – mopo922 May 16 '15 at 22:54
  • 2
    @Justin I think that is because localhost tries to use socket, while 127.0.0.1 uses TCP. – pebbo Aug 19 '15 at 13:32
  • thanks, this worked for me after changing `DB_HOST` in the .env to `127.0.0.1` instead of `localhost`. – Abdallah Alsamman Dec 17 '15 at 13:50
  • 1
    If you're using Homestead you need to check your `Homestead.yaml` file for the correct ip address. In the most recent versions of Homestead the default is `192.168.10.10`, so using `127.0.0.1` will result in the same error. – Tom Leu Dec 23 '15 at 23:23
  • @SamuelFullman (and other MAMP users) -- For me, I had to add the port number (8889) to the host, i.e., `127.0.0.1:8889`. Oddly, the IP address does NOT work for me when accessing my app via web browser, but `localhost` does -- and vice versa for CLI. :/ – Soulriser Jan 14 '16 at 20:26
  • @Soulriser it depends on the port specified in your MAMP preferences, if you go to preferences you can click the button to set the default MAMP port to port 80 and therefore don't need to set a port number to 127.0.0.1. However, if you do have another port set like 8889, you will have to append that like 127.0.0.1:8889. I usually set it to the default port 80 because it is easier. But good catch :) – stuyam Jan 14 '16 at 21:10
  • 1
    worked as magic , I also want to assure that the port of mysql have to be 8889 – mercury Feb 08 '16 at 03:04
  • Also try to clear laravel cashe by (php artisan config:clear) – mercury Feb 16 '16 at 01:27
  • This worked for me too but what if i changed the ip in Homestead.yaml file to 127.0.0.1, would i run into any troubles with homestead? – fokosun Apr 20 '16 at 17:48
  • @Picrasma that is actually what it should be set at, I updated the answer because it should be at 127.0.0.1 because that runs locally in the homestead vm – stuyam Apr 20 '16 at 18:32
  • 1
    thankyou so much, was trying to fix this for days! (running xampp on mac) – rsharma May 25 '16 at 15:51
  • 21
    `A Unix socket file is used if you do not specify a host name or if you specify the special host name localhost.` http://dev.mysql.com/doc/refman/5.7/en/can-not-connect-to-server.html – x-yuri Aug 17 '16 at 17:22
  • This worked for me, but only after I shut down the Laravel server, and ran 'php artisan serve' again. – carbide20 Apr 21 '17 at 16:39
  • @carbide20 whenever you change an env you have to restart Laravel before it will take effect. – stuyam Apr 21 '17 at 18:36
  • Using MAMP Pro - I had to check "Allow network access to MySQL" to make it work. – Toby Beresford Mar 26 '18 at 15:33
  • 1
    Same solution for Yii2 projects! – Stefan Vilbrandt May 04 '18 at 14:46
  • 1
    changing the HOST parameter in .env worked perfectly on Laravel 5.6 – nensamuel May 18 '18 at 13:17
  • _“the "local internet" on your computer being much more reliable than the UNIX socket”_ AFAIK this is not about reliability but configuration (at least in [my case](https://superuser.com/q/938794/84807)): The access through UNIX socket can be forbidden while TCP works. – Melebius Mar 17 '21 at 11:07
  • in .env set: DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=null DB_DATABASE=yourdatabase DB_USERNAME=youruder DB_PASSWORD=yourpassword – Wellington Oliveira May 17 '21 at 01:57
  • I deployed laravel project with sail and in my case I had to change localhost/127.0.0.1 to mysql containers name (e.g. myproject_mysql), the funny thing is: migrations and other php artisan database related commands will run only from container, or you have to change env DB_HOST to 127.0.0.1 again before running migrations. – Vsevolod Jun 29 '22 at 08:13
167

The error message indicates that a MySQL connection via socket is tried (which is not supported).

In the context of Laravel (artisan), you probably want to use a different / the correct environment. Eg: php artisan migrate --env=production (or whatever environment). See here.

ukautz
  • 2,193
  • 1
  • 13
  • 7
  • 2
    This was the solution to my problem, one of the developers at our company doesn't use Homestead and connects to mysql via socket. I removed the socket config within my app/database.php file. Problem solved – borislemke Jan 29 '16 at 06:06
  • I just had to enable mysqli.so extension in php.ini – Mehulkumar Apr 23 '17 at 09:42
  • 6
    I had to add "'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock'" to config/database.php – Ángel Carlos del Pozo Muela Jan 31 '18 at 12:23
  • hello community , i am getting this error even though i am not using laravel can you look at the problem here it is https://stackoverflow.com/questions/60796332/this-php-code-works-in-localhost-but-not-on-server – Kiran Patel Mar 22 '20 at 05:57
  • This also happens when you use socket as MySQL endpoint, and the MySQL service simply does not run. – Sych Jul 12 '20 at 15:16
115

I got the same problem and I'm running Mac OS X 10.10 Yosemite. I have enabled the Apache Server and PHP that already comes with the OS. Then I just configured the mCrypt library to get started. After that when I was working with models and DB I got the error:

[PDOException]
SQLSTATE[HY000] [2002] No such file or directory

The reason I found is just because PHP and MySQL can't get connected themselves. To get this problem fixed, I follow the next steps:

  1. Open a terminal and connect to the mysql with:

    mysql -u root -p
    
  2. It will ask you for the related password. Then once you get the mysql promt type the next command:

    mysql> show variables like '%sock%'
    
  3. You will get something like this:

    +-----------------------------------------+-----------------+
    | Variable_name                           | Value           |
    +-----------------------------------------+-----------------+
    | performance_schema_max_socket_classes   | 10              |
    | performance_schema_max_socket_instances | 322             |
    | socket                                  | /tmp/mysql.sock |
    +-----------------------------------------+-----------------+
    
  4. Keep the value of the last row:

    /tmp/mysql.sock
    
  5. In your laravel project folder, look for the database.php file there is where you configure the DB connection parameters. In the mysql section add the next line at the end:

    'unix_socket' => '/tmp/mysql.sock'
    
  6. You must have something like this:

    'mysql' => array(
            'driver'    => 'mysql',
            'host'      => 'localhost',
            'database'  => 'SchoolBoard',
            'username'  => 'root',
            'password'  => 'venturaa',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'unix_socket' => '/tmp/mysql.sock',
        ),
    

Now just save changes, and reload the page and it must work!

M--
  • 25,431
  • 8
  • 61
  • 93
alexventuraio
  • 8,126
  • 2
  • 30
  • 35
  • 4
    The most "straight to issue" solution. Thanx, this fixed me on running Laravel with MAMP pro – animaacija Jun 25 '15 at 07:38
  • Thanks for this. This worked for me. Using OSX 10.10.5 MAMP Pro – marknt15 Nov 05 '15 at 04:45
  • This worked for me as well with MAMP pro and OS X 10.11.x. Ended up being: `/Applications/MAMP/tmp/mysql/mysql.sock` – Bort License Plate Jan 20 '16 at 04:47
  • 1
    +1. Using "127.0.0.1" in the config instead of "localhost" as Yamartino said in his answer works well but it's quicker with a socket and this answer solves the problem. It's a shame mysql treats "localhost" in such a peculiar way when unix_socket is defined though... – Shautieh Feb 20 '16 at 06:10
  • @GregFerrell Yeah that's true but well... I hope it could be useful – alexventuraio Feb 20 '16 at 06:37
  • Worked fine on Linux vps, laravel 5! – Nika Tsogiaidze Jun 05 '17 at 08:06
  • This works like a charm! any idea as to why PHP and MySQL can't communicate? – vnay92 Feb 22 '18 at 13:01
  • @vnay92 I'm not sure but I think it's because of the installation paths of MySQL or for PHP that may varies depending on OS or PHP distributions, I guess! – alexventuraio Feb 22 '18 at 19:59
  • I did everything you said, but had no succes :( actually nothing changed... i'm using docker compose and I have a few docker instances running.. does that change anything? – Gabriel Augusto Dec 17 '18 at 18:13
  • @GabrielAugusto absolutely that changes a lot since docker instances are isolated from each other and they need special configuration to access a db or a shared db server between docker instances. So I recommend you to digging a bit more into Docker and DB servers. Because that is out of the scope of this answer. – alexventuraio Dec 20 '18 at 00:49
  • This was the solution to the problem – Armin Oct 01 '19 at 09:24
  • Thanks for the answer, worked for me as well. For better maintenance I suggest leaving the config/database.php alone and adding `DB_SOCKET = path.to.mysql.lock ` to the .env file – teutara Jan 08 '20 at 15:44
  • MySQL treating `localhost` in a "peculiar way" is because sockets are essentially files, and permissions/everything-security-related can be configured to work much effectively through them, without resolving to TCP. For that reason when you do `sudo mysql -u root` you don't even need to provide a root password, as `sudo` acts as root user and grants you root access. Thus, the connections via sockets are more elegant. – Gelmir Jun 28 '21 at 11:36
  • @ShahriyarImanov thanks for the clarification and the constructive comment. – alexventuraio Jun 30 '21 at 17:56
  • if you have tried every other solution with no success, then this solution is your last resort. it worked for me, particularly on Laravel 5.8 on OS X – Macdonald Mar 30 '22 at 10:29
53

I encountered the [PDOException] SQLSTATE[HY000] [2002] No such file or directory error for a different reason. I had just finished building a brand new LAMP stack on Ubuntu 12.04 with Apache 2.4.7, PHP v5.5.10 and MySQL 5.6.16. I moved my sites back over and fired them up. But, I couldn't load my Laravel 4.2.x based site because of the [PDOException] above. So, I checked php -i | grep pdo and noticed this line:

pdo_mysql.default_socket => /tmp/mysql.sock => /tmp/mysql.sock

But, in my /etc/my.cnf the sock file is actually in /var/run/mysqld/mysqld.sock.

So, I opened up my php.ini and set the value for pdo_mysql.default_socket:

pdo_mysql.default_socket=/var/run/mysqld/mysqld.sock

Then, I restarted apache and checked php -i | grep pdo:

pdo_mysql.default_socket => /var/run/mysqld/mysqld.sock => /var/run/mysqld/mysqld.sock

That fixed it for me.

dcarrith
  • 7,510
  • 2
  • 18
  • 9
  • This was the fix that worked for me , the problem was that I installed two versions of mysql and removed one , the 127.0.0.1 change didn't work or adding the sock in the config , thanks ! @dcarrith – Luis Oct 27 '15 at 02:32
  • 2
    This helped me find my problem - which was that I was using OSX bundled php, not the MAMP php binary. So make sure you are using the right version of php that points to the correct php.ini, etc. Definite "doh!" moment. – dragonflyesque Apr 05 '16 at 18:43
48

The answer from @stuyam solved the "No such file or directory" issue for me

Short answer: Change "host" in the /app/config/database.php file from "localhost" to "127.0.0.1"

But then I had a "Connection refused" error. If anyone had the same issue, my solution for this was to update the app/config/local/database.php file so the port is 8889:

'mysql' => array(
        'driver'    => 'mysql',
        'host'      => '127.0.0.1',
        'port'      => '8889',
        'database'  => 'databaseName',
        'username'  => 'root',
        'password'  => 'root',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
    ),
stuyam
  • 9,561
  • 2
  • 21
  • 40
Marlow
  • 481
  • 4
  • 4
30

In my case i had no problem at all, just forgot to start the mysql service...

sudo service mysqld start
Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
Carlos ABS
  • 693
  • 9
  • 19
26

If you are using Laravel Homestead, make sure you're calling the commands on the server.

homestead ssh

Then simply cd to the right directory and fire your command there.

Koeno
  • 1,493
  • 2
  • 16
  • 30
24

It worked after I change from DB_HOST=localhost to DB_HOST=127.0.0.1 at .env file

noone
  • 6,168
  • 2
  • 42
  • 51
22

This is because PDO treats "localhost" host specially:

Note: Unix only: When the host name is set to "localhost", then the connection to the server is made thru a domain socket. If PDO_MYSQL is compiled against libmysqlclient then the location of the socket file is at libmysqlclient's compiled in location. If PDO_MYSQL is compiled against mysqlnd a default socket can be set thru the pdo_mysql.default_socket setting.

(from http://php.net/manual/en/ref.pdo-mysql.connection.php)

Changing localhost to 127.0.0.1 will "force" the use of TCP.

Note: mysqli_connect is working fine with localhost.

Thomas Decaux
  • 21,738
  • 2
  • 113
  • 124
21

Add mysql.sock path in database.php file like below example

'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',

Eample

'mysql' => [
        'driver' => 'mysql',
        'unix_socket' => '/Applications/MAMP/tmp/mysql/mysql.sock',
        'host' => env('DB_HOST', 'localhost'),
        'port' => env('DB_PORT', '8889'),
Ravichandran
  • 1,029
  • 6
  • 11
20

Mamp user enable option Allow network access to MYSQL

enter image description here

George John
  • 2,629
  • 2
  • 21
  • 16
15

Step 1

Find the path to your unix_socket, to do that just run netstat -ln | grep mysql

You should get something like this

unix  2      [ ACC ]     STREAM     LISTENING     17397    /var/run/mysqld/mysqld.sock

Step 2

Take that and add it in your unix_socket param

'mysql' => array(
            'driver'    => 'mysql',
            'host'      => '67.25.71.187',
            'database'  => 'dbname',
            'username'  => 'username',
            'password'  => '***',
            'charset'   => 'utf8',
            'collation' => 'utf8_unicode_ci',
            'prefix'    => '',
            'unix_socket'    => '/var/run/mysqld/mysqld.sock' <-----
            ),
        ),

Hope it helps !!

Community
  • 1
  • 1
code-8
  • 54,650
  • 106
  • 352
  • 604
14

Building on the answer from @dcarrith ...

Instead of editing the config files, I created an alias in the location that PHP is looking that connects to the real mysql.sock. (source)

Just run these two commands (no restart needed):

mkdir /var/mysql
ln -s /tmp/mysql.sock /var/mysql/mysql.sock
Community
  • 1
  • 1
Justin
  • 26,443
  • 16
  • 111
  • 128
8

I'm running on MAMP Pro and had this similar problem when trying to migrate (create db tables). Tried a few of these mentioned suggestions as well but didn't do it for me.

So, simply (after an hour googling), I added two things to the /config/database.php.

'port' => '1234',
'unix_socket' => '/path/to/my/socket/mysqld.sock'

Works fine now!

anoraq
  • 515
  • 7
  • 9
8

Just i do one change in .env file

I have following line of code.

DB_CONNECTION=mysql
DB_HOST=localhost
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=

Change host name localhost to 127.0.0.1

DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=database_name
DB_USERNAME=root
DB_PASSWORD=

That is work in my case because that can't find any hostname like localhost

And after changing hostname write following command

php artisan config:clear
php artisan migrate:install
php artisan migrate
Alp Altunel
  • 3,324
  • 1
  • 26
  • 27
Rinkal Jasani
  • 472
  • 5
  • 7
6

I had this problems when I was running my application using docker containers.

The solution was put the name of the MySQL service container I was using in docker_compose.yml on DB_HOST. In my case, it was db :

DB_HOST=db

Hope it helps.

Lano
  • 593
  • 1
  • 7
  • 13
4

I had similar problems accessing my Drupal website. I fixed it by opening the command line, and restarting my MySQL server or service:

service mysqld restart

This should work. If it doesn't, restart your local webserver:

service httpd restart

That should be enough. Hope it works for other environments, too. Note that these commands generally require superuser privileges.

Cody Gray - on strike
  • 239,200
  • 50
  • 490
  • 574
RAWGIT
  • 99
  • 1
  • 3
4

I ran into this problem when running PHPUnit in Elixir/Gulp, and Homestead as my Vagrant enviroment.

In my case I edited the .env file from DB_HOST=localhost to DB_HOST=192.168.10.10 where 192.168.10.10 is the IP of my Vagrant/Homestead host.

4

Check your port carefully . In my case it was 8889 and i am using 8888. change "DB_HOST" from "localhost" to "127.0.0.1" and vice versa

Ahmed Awan
  • 347
  • 3
  • 9
4

I had the same problem using Docker and MySQL service name db in docker_compose.yml file:

I added the following in the .env file:

DB_HOST=db

you should also assure that your host is discoverable from the php app.

It was because PHP didn't figure out which host to use to connect.

Oscar Gallardo
  • 2,240
  • 3
  • 27
  • 47
  • Same issue here, was still using `DB_HOST=localhost` and got `SQLSTATE[HY000] [2002] No such file or directory` when changing it to `DB_HOST=127.0.0.1`, the error changed to `SQLSTATE[HY000] [2002] Connection refused`. Only when I changed it into the name of the MySQL docker container did it start working, ie: `DB_HOST=mysql` in my case. Not sure why that works, when other answers claim it has to do with sockets, my guess is some kind of fallback mechanism with incorrect checks throwing misleading errors. – xorinzor Sep 20 '21 at 15:40
3

I got the same problem in ubuntu 18.04 with nginx. By following the below steps my issue has been fixd:

First open terminal and enter into mysql CLI. To check mysql socket location I write the following command.

mysql> show variables like '%sock%'

I got something like the below :

+-----------------------------------------+-----------------------------+
| Variable_name                           | Value                       |
+-----------------------------------------+-----------------------------+
| mysqlx_socket                           | /var/run/mysqld/mysqlx.sock |
| performance_schema_max_socket_classes   | 10                          |
| performance_schema_max_socket_instances | -1                          |
| socket                                  | /var/run/mysqld/mysqld.sock |
+-----------------------------------------+-----------------------------+
4 rows in set (0.00 sec)

In laravel project folder, look for the database.php file in the config folder. In the mysql section I modified unix_socket according to the above table.

'mysql' => array(
        'driver'    => 'mysql',
        'host'      => '127.0.0.1',
        'database'  => 'database_name',
        'username'  => 'username',
        'password'  => 'password',
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'unix_socket' => '/var/run/mysqld/mysqld.sock',
    ),

Now just save changes, and reload the page and it worked.

Hasinur
  • 194
  • 1
  • 6
2

As of Laravel 5 the database username and password goes in the .env file that exists in the project directory, e.g.

DB_HOST=127.0.0.1
DB_DATABASE=db1
DB_USERNAME=user1
DB_PASSWORD=pass1

As you can see these environment variables are overriding the 'forge' strings here so changing them has no effect:

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', 'localhost'),
        'database'  => env('DB_DATABASE', 'forge'),
        'username'  => env('DB_USERNAME', 'forge'),
        'password'  => env('DB_PASSWORD', ''),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

More information is here https://mattstauffer.co/blog/laravel-5.0-environment-detection-and-environment-variables

malhal
  • 26,330
  • 7
  • 115
  • 133
2

Attempt to connect to localhost:

SQLSTATE[HY000] [2002] No such file or directory

Attempt to connect to 127.0.0.1:

SQLSTATE[HY000] [2002] Connection refused

OK, just comment / remove the following setting from my.cnf (on OS X 10.5: /opt/local/etc/mysqlxx/my.cnf) to obtain:

[mysqld]
# skip-networking

Of course, stop and start MySQL Server.

Anna Logg
  • 39
  • 1
2

solved

in my case it was a logic issue in code, the connection values are in a if statement:

if($_SERVER['HTTP_HOST'] == "localhost")

so the solution was to add a pipe and add 127.0.0.1, that solved the problem for me

if($_SERVER['HTTP_HOST'] == "localhost" || $_SERVER['HTTP_HOST'] == "127.0.0.1")
Saleh Abdulaziz
  • 1,115
  • 9
  • 15
1

If you are using Laravel Homestead, here is settings

(include Vagrant-Virtual Machine)

.bash-profile

alias vm="ssh vagrant@127.0.0.1 -p 2222"

database.php

    'mysql' => [
        'driver'    => 'mysql',
        'host'      => env('DB_HOST', '127.0.0.1'),
        'database'  => env('DB_DATABASE', 'homestead'),
        'username'  => env('DB_USERNAME', 'homestead'),
        'password'  => env('DB_PASSWORD', 'secret'),
        'charset'   => 'utf8',
        'collation' => 'utf8_unicode_ci',
        'prefix'    => '',
        'strict'    => false,
    ],

Terminal

vm

vagrant@homestead:~/Code/projectFolder  php artisan migrate:install
ErcanE
  • 1,571
  • 3
  • 19
  • 28
1

If anyone are still looking for the answer, just check your .env file. For some reason laravel create a .env.example file, so all this answers didn't work for me. I fixed my issue renamming .env.example to .env

Alberto Alegria
  • 1,023
  • 10
  • 26
  • There's no single correct answer to this question as there are a variety of errors that can be made. This is one of them, as is failing to copy the .env file to a remote server. So it's worth checking the .env file on the server where you're trying to run the query to ensure that it both exists and contains the necessary information to make a connection. – petercoles Feb 09 '16 at 10:26
1

This happened to me because MySQL wasn't running. MySQL was failing to start because I had a missing /usr/local/etc/my.cnf.d/ directory.

This was being required by my /usr/local/etc/my.cnf config file as a glob include (include /usr/local/etc/my.cnf.d/*.cnf).

Running mkdir /usr/local/etc/my.cnf.d, and then starting MySQL, fixed the issue.

james2doyle
  • 1,399
  • 19
  • 21
1

In my case, I was running php artisan migrate on my mac terminal, when I needed to ssh into vagrant and run it from there. Hope that helps someone the headache.

Brad
  • 12,054
  • 44
  • 118
  • 187
1

In my case I had to remove the bootstrap/cache folder and try it again.

My cenario was after a server migration.

UPDATED AND WORKING

  1. Remove folder "cache" from bootstrap (booststrap/cache)
  2. Copy folder "cache" from original folder and paste it in bootstrap
  3. Run these commands: 3.1) php artisan config:cache 3.2) php artisan migrate 3.3) php artisan db:see 3.4) php artisan serve

That's all.

Raphael Cangucu
  • 191
  • 1
  • 5
  • that solve my problem. I was try to create db using `php artisan db:create` . although just before this command I have a DB but I was in need to fresh db. , but I faced. there was no single change that affect the mysql connection – Ahmed Bahtity Apr 12 '21 at 23:43
0

When using a VirtualMachine make sure you ssh into that machine and navigate to your App folder and call the php artisan migrate command from there.

cmac
  • 3,123
  • 6
  • 36
  • 49
0

In may case, I'd simply used

vagrant up

instead of

homestead up

for my forge larval setup using homestead. I'm assuming this meant the site was getting served, but the MySQL server wasn't ever booted. When I used the latter command to launch my vagrant box, the error went away.

Ben Wilson
  • 2,271
  • 3
  • 26
  • 35
0

All these answers seem like heavy lifting...

I just created a .env file; edited my bootstrap/app.php file, and uncommented the following line...

Dotenv::load(__DIR__.'/../');

Hope this helps someone

MrMesees
  • 1,488
  • 19
  • 27
0

For anyone trying to create a fresh db connection not on laravel but bumped here seeking for answers to run PDO from the Terminal. This would be of help to you. And you can refactor it to work best for you.

<?php

class db
{
   private $DBHOST = 'localhost'; // you don't need 127.0.0.1
   private $DRIVER = 'mysql';
   private $PORT   = '8888'; // database port. 8888 is mine
   private $DB     = 'example-db';
   private $PASS   = 'example-pass';
   private $USER   = 'root';
   private $SOCKS  = ''; // can fill this or leave blank.


   // - connect (dummy connection)
   private function con()
   {
       if ($this->SOCKS == '')
       {
           // run shell command to get 
           $socks = shell_exec('netstat -ln | grep mysql');
           $socks = trim(substr($socks, strpos($socks, '/')));

           $this->SOCKS = strlen($socks) > 0 ? ';unix_socket='.$socks : '';
       }
       else
       {
          $this->SOCKS = ';unix_socket='.$this->SOCKS;
       }

       $dsn = $this->DRIVER.':host='.$this->DBHOST.';dbname='.$this->DB;

       // add socks
       $dsn .= $this->SOCKS;

       // add port
       $dsn .= (strlen($this->PORT) > 0) ? ';port='.$this->PORT : '';

       // extablish connection
       $con = new PDO($dsn, $user, $pass);

       // return PDO instance.
       return $con;
   }
   // - ends here

   // now you can call $this->con() within class to use connection 
   // would run fine on any terminal

} 

hope it helps!

Ifeanyi Amadi
  • 776
  • 5
  • 10
0

My answer is specific to Laravel.

I had this message after creating a new connection in the database.php configuration file to a local Docker MySQL service and setting it as the default connection. I forgot that I was setting a different connection by overwriting it in the Model:

class Model extends \Illuminate\Database\Eloquent\Model
{
    protected $connection;

    public function __construct(array $attributes = [])
    {
        parent::__construct($attributes);
        $this->connection = 'some_other_connection';
    }
...

So even if my default connection in the database.php file was pointing to the right credentials, the model was still using the remote database connection configuration which I had removed from the local environment file.

Patrick.SE
  • 4,444
  • 5
  • 34
  • 44
0

To add to @alexventuraio's solution, if you are experiencing this issue on Laravel 5.8, you might want to replace the value of 'unix_socket' in your database config file as thus:

 'mysql' => [
        'driver' => 'mysql',
        'host' => env('DB_HOST', '127.0.0.1'),
        'port' => env('DB_PORT', '3306'),
        'database' => env('DB_DATABASE', 'forge'),
        'username' => env('DB_USERNAME', 'forge'),
        'password' => env('DB_PASSWORD', ''),
        // 'unix_socket' =>'/var/run/mysqld/mysqld.sock',
        'unix_socket' => env('DB_SOCKET', ''), // replace with this line, so you can always add the mysqld.sock from the dotenv file
        'charset' => 'utf8mb4',
        'collation' => 'utf8mb4_unicode_ci',
        'prefix' => '',
        'prefix_indexes' => true,
        'strict' => false,
        'engine' => null,
        'options' => extension_loaded('pdo_mysql') ? array_filter([
            PDO::MYSQL_ATTR_SSL_CA => env('MYSQL_ATTR_SSL_CA'),
        ]) : [],
    ],
Macdonald
  • 880
  • 7
  • 21
0

All the existing answers are correct and might work for you. My case was a bit different. I encountered this error when I started a docker project locally using docker-compose up.

The problem for my specific case was that I ran the docker-compose up from a sub-folder instead of the root folder in which the docker-compose file lies.

Make sure you run docker-compose up from the folder where the docker-compose.yml is saved to!

josias
  • 1,326
  • 1
  • 12
  • 39
0

Check your MySQL server is running, if database connection is correct configured.