Often times you may come across an error that outputs "PDOException SQLSTATE[HY000] [2002] No such file or directory" in Laravel. This error typically appears when you want to run a database migration and there are several possible ways to fix this.
The first thing to note is that you need to have MySQL installed and running on your machine. Depending on your operating systems there are several possible ways to install MySQL.
Step 1: Check if MySQL is installed and Running on Your Machine
The first thing to note is that you need to have MySQL installed and running on your machine. Depending on your operating systems there are several possible ways to install MySQL.
- Using MySQL provided by Laravel Homested
- Using MySQL provided by DBngin (macOS only)
- Using MySQL provided by the Native Installer
- Using MySQL provided by XAMPP / WAMP & etc
Step 2: Update Your Laravel .env Environment File
Now make sure to update your Laravel environment file (.env) DB_* configs. Do note that for the DB_HOST it's specified as 127.0.01 instead of the default "localhost".
DB_CONNECTION=mysql DB_HOST=127.0.01 DB_PORT=3306 DB_DATABASE=your_db_name_here DB_USERNAME=root DB_PASSWORD=
Step 3: Clear Config and Run Migration Command
Now that you have done the steps above you need to clear your configuration file cache by running the code below.
php artisan config:clear
And try to migrate once again.
php artisan migrate
Other Options: Restart MySQL
Sometimes this can be caused by not having MySql running on the machine. If that's the case do start MySql and try the code once again. If you are using Ubuntu then you can run the code below.
sudo service mysqld start
If you are on macOs and you are using homebrew run the service command.
brew services restart mysql
On windows, if you are using a GUI app like XAMPP just start it using the start button. If you do have any other suggestions do comment down below and let's start the discussion, Cheers!.