Laravel/Homestead数据库迁移失败求助:终端执行php artisan migrate报错
Hey there, let's break down why your Laravel app can talk to the Homestead database just fine, but running php artisan migrate in the terminal throws that access denied error. The key here is environment context—your app runs inside the Homestead VM, but you might be running the migrate command in a different environment.
Most Common Fix: Run Migrate Inside the Homestead VM
Your Laravel app lives and runs inside the Homestead virtual machine, where the database is directly accessible via localhost. If you're running php artisan migrate on your local machine's terminal (not inside the VM), your local PHP is trying to connect to a database it can't reach properly. Here's how to fix this:
- Open your terminal and navigate to your Homestead directory (where
Homestead.yamllives). - SSH into the VM with:
homestead ssh # Or vagrant ssh if that's what you use - Move into your project directory (default path is
/home/vagrant/code/your-project-name). - Now run the migrate command:
php artisan migrate
This uses the VM's native PHP and database connection settings—exactly what your app uses—so it should work without issues.
If You Want to Run Migrate Locally (Not Recommended, But Possible)
If you really need to run the command on your local machine, you'll need to adjust your .env settings to match Homestead's port forwarding:
- Open your project's
.envfile and update these values:DB_HOST=192.168.10.10 # Default Homestead IP, check your Homestead.yaml to confirm DB_PORT=33060 # Homestead maps VM port 3306 to local port 33060 DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret - Clear your Laravel config cache to pick up the changes:
php artisan config:clear - Try running
php artisan migrateagain locally.
Troubleshooting If You're Already Inside the VM
If you're SSH'd into Homestead and still getting the error, check these things:
- Verify your VM's
.envfile: Make sure it has the default Homestead DB credentials:DB_HOST=localhost DB_DATABASE=homestead DB_USERNAME=homestead DB_PASSWORD=secret - Clear config cache: Sometimes old config sticks around:
php artisan config:clear - Check database user permissions: Log into the Homestead MySQL instance to confirm the
homesteaduser has access fromlocalhost:- Run
mysql -u homestead -pand entersecretwhen prompted. - Run this SQL query:
SELECT user, host FROM mysql.user; - If
homestead@localhostisn't listed, create and grant permissions:CREATE USER 'homestead'@'localhost' IDENTIFIED BY 'secret'; GRANT ALL PRIVILEGES ON *.* TO 'homestead'@'localhost'; FLUSH PRIVILEGES;
- Run
- Sync your shared folders: If your local
.envchanges aren't showing up in the VM, reload Homestead with provisioning:# Run this on your local terminal, not inside the VM vagrant reload --provision
内容的提问来源于stack exchange,提问作者prgrm

