Run tests from host on a Homestead MySQL server

The Problem

Being ruined by the lightness and speed of Laravel Valet on my personal machine, and since Valet is not available on Ubuntu officially, a couple of years ago I decided to install all my stack locally and move away from Laravel Homestead, which is a vagrant development-ready image..

All worked well, until I did the same when I moved to Mawdoo3.com, for some reason (If you know what's wrong, save my ass please), connecting to MySQL works fine, querying MySQL is fine, but paginating results is not fine, just keeps returning the same content over and over. moving the code to another machine works like a charm.

Unfortunately, I could not figure out what's wrong and I had little time to tinker around, so I went with Homestead again. Sure enough, 15 minutes later I was up and running.

Nowadays, I use a package called PHPUnitKit to run my tests from within Sublime, this enables me to run a single test, last test, current test file or the whole suite. and for the projects I'm working on, there's some migrations that are not supported on the Sqlite driver so I'm forced to use a dummy Mysql database to run my tests on.

The problem is that when I run my tests from Sublime, we're still using the same .env file which has port 3306 for the database connection, where I should be using the already forwarded port 33060 to hit the database in the vm. But now if I run the tests from within the vm I'll get an error because I should be using port 3306 not port 33060.

And in a circle, I loop.

The Workaround

For this workaround to work, we need to have MySQL installed on our host machine so that Sublime can use it behind the scenes, you can install it like so if you don't have it already

sudo apt update && sudo apt install mysql-server

Great, now we need to forward the local port 3306 to the vm port 3306 so that it doesn't matter whether we're connecting from outside or inside the vm, it's still the same port and host in the .env file. we can do this easily with Homestead, we just need to list our port with the forwarded ports list in Homestead.yaml.

ports:
- send: 3306
to: 3306

The only thing we need to do now is to make sure Mysql is not running on the host otherwise the port will not be available, you can just run sudo service mysql stop and then restart and provision the vm again. to avoid running this command every time you restart the host, you may run sudo systemctl disable mysql to disable MySQL from the startup sequence.

# From within the Homestead folder
vagrant reload --provision

Now we should be able to access the MySQL server inside the vm from both the host and guest at 127.0.0.1:3306

Would love a conversation if you have a more elegant solution => [email protected]