
Step-by-Step Solution:
- Locate the .env File:
- The
.env
file is located in the root directory of your PHP or Laravel application. This file contains key-value pairs for environment-specific configurations.
- The
- Edit the .env File:
- Open the
.env
file in a text editor, such as VSCode or Sublime Text.
- Open the
- Add the DB_SOCKET Configuration:
- Inside the
.env
file, add the following line to specify the MySQL socket location:DB_SOCKET=/opt/lampp/var/mysql/mysql.sock
- This line tells your application where to find the MySQL socket file, which resolves the connection refusal when using a local development environment like XAMPP.
- Inside the
- Verify Other Database Configuration:
- Ensure that your database connection settings are correctly set. Below is an example of a full database configuration block in the
.env
file:
- Ensure that your database connection settings are correctly set. Below is an example of a full database configuration block in the
DB_CONNECTION=mysql
DB_HOST=127.0.0.1
DB_PORT=3306
DB_DATABASE=your_database_name
DB_USERNAME=your_database_user
DB_PASSWORD=your_database_password
DB_SOCKET=/opt/lampp/var/mysql/mysql.sock
5. Save the .env File:
- After adding the socket configuration, save the
.env
file.
6. Clear Route, Cache, and Optimize the Application:
- Once you’ve updated the
.env
file, it’s essential to clear and optimize the Laravel application’s cache, routes, and configuration. This will ensure your changes are reflected and improve the application’s performance. Run the following commands from your terminal:
php artisan config:cache # Clear and cache the configuration files
php artisan route:cache # Clear and cache the route files
php artisan cache:clear # Clear the application's cache
php artisan optimize # Optimize the application's performance
Conclusion: By adding the DB_SOCKET
line to your .env
file, you can easily fix the Connection refused
error caused by socket connection issues in local PHP environments like XAMPP. This simple change can save you a lot of troubleshooting time and get your PHP application connecting to MySQL without errors.