Laravel 5.5项目如何切换连接至XAMPP数据库?
Hey there! I’ve been in this exact spot before—juggling a standalone MySQL CLI and XAMPP, and needing to switch Laravel to use XAMPP’s database instead. Let’s walk through the simple steps to get this sorted:
Step 1: Confirm XAMPP's MySQL Details First
First things first, make sure your XAMPP MySQL service is up and running. Open the XAMPP Control Panel and check that the MySQL module shows a green "Running" status.
You’ll need these key details from XAMPP’s setup:
- Host: Almost always
127.0.0.1(localhost works too, but127.0.0.1avoids some DNS quirks) - Port: Default is
3306—if you changed it in XAMPP’s config, use that custom port - Username: Default is
root - Password: By default, XAMPP’s MySQL has no password. If you set one during XAMPP setup, use that password
- Database Name: The name of the database you created (or want to create) in phpMyAdmin
Step 2: Update Laravel's Environment Configuration
Laravel uses the .env file in your project root for database settings—this is where we’ll make the switch.
Open the .env file, find the database section, and replace the values with your XAMPP MySQL details:
DB_CONNECTION=mysql DB_HOST=127.0.0.1 DB_PORT=3306 DB_DATABASE=your_xampp_database_name # Replace with your actual db name from phpMyAdmin DB_USERNAME=root DB_PASSWORD= # Leave empty if no password, or fill in your set password
Important: Clear Configuration Cache
If you’ve run config caching commands before, you’ll need to clear the cache so Laravel picks up the new settings. Run this in your project’s terminal:
php artisan config:clear
You can also run php artisan config:cache later if you want to cache the new settings for better performance.
Step 3: Test the Connection
To confirm everything works, try running your migration command again:
php artisan migrate
If it runs without errors, you’re all set!
For a quick visual check, add a test route in routes/web.php:
Route::get('/test-db-connection', function () { try { \Illuminate\Support\Facades\DB::connection()->getPdo(); return "<h1>Success! Connected to XAMPP's MySQL database.</h1>"; } catch (\Exception $e) { return "<h1>Connection Failed:</h1><p>" . $e->getMessage() . "</p>"; } });
Then visit http://your-project-url/test-db-connection in your browser to see the result.
Troubleshooting Common Issues
- "Access denied for user 'root'@'localhost'": Double-check your password—remember XAMPP’s default is empty. If you set a password, make sure it’s correct.
- "Connection refused": Ensure XAMPP’s MySQL service is running, and that the
DB_PORTin.envmatches the port XAMPP is using. You can find the port in XAMPP’s MySQL config file (look forport = 3306inmy.iniormy.cnf). - "Database not found": Make sure the
DB_DATABASEname matches exactly what you created in phpMyAdmin (case-sensitive on some systems).
内容的提问来源于stack exchange,提问作者Priyanka Sankhala

