No such file or directory error in Laravel and mysql database
The error "Illuminate\Database\QueryException : SQLSTATE[HY000] [2002] No such file or directory" usually occurs while configuring MySQL database with Laravel. There can be many but one of the main reason in Laravel 7+ is the 'unix_socket' variable. We must properly add this variable according to the underlying operating system (Windows, Mac, etc.)
For Mac OS we must add the following line in the .env file:
UNIX_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock.
One important point to remember here is that by default in Laravel 8+ the UNIX_SOCKET variable name in the database.php file is a little different from the older version of Laravel. If we closely look at the database.php file it assumes the unix_socket variable to be 'DB_SOCKET' in the environment file. Means it is DB_SOCKET, not UNIX_SOCKET.
This can be done in the following two ways:
Method 1.
In .env file set the following variable
DB_SOCKET=/Applications/MAMP/tmp/mysql/mysql.sock.Method 2.
In database.php file change the following
'unix_socket' => env('DB_SOCKET', ''),To
'unix_socket' => env('DB_SOCKET', '/Applications/MAMP/tmp/mysql/mysql.sock'),This will fix the 'No such file or directory error' in the local machine. If you are deploying your laravel application on Google Cloud or AWS please remove the usnix_socket line from the database.php file. If you don't, your application will throw an exception.