Datadog collects and monitors your PHP app metrics and distributed traces in real-time with application performance monitoring. Decrease downtime and performance issues with Datadog APM by tracing requests across service boundaries and drilling into individual traces end-to-end with flame graphs. Start your 14-day trial for free today.

Easily switch PHP versions in Laravel Valet

Original – by Freek Van der Herten – 2 minute read

Besides enjoying some greenfield work, we often have to work on legacy projects at Spatie too. Sometimes those projects don't run on the latest PHP version. I this blogpost I'd like to show you a way to switch PHP version easily when using Laravel Valet. (I know you could also use Docker or Virtualbox to solve this problem, but that's out of scope for this blogpost.)

I'm going to assume that you already use the latest versions of homebrew, Laravel Valet and have PHP 7.2 installed. In order to easily switch PHP versions you first should install the older versions of PHP.

Run these commands in your terminal

brew install php@7.0
brew install php@7.1

Next were are going to define a bash function and some aliases to easily switch the current PHP version. If you don't know how to create a bash function and where to put this code, read this blogpost first.

phpv() {
    valet stop
    brew unlink php@7.0 php@7.1 php@7.2
    brew link --force --overwrite $1
    brew services start $1
    composer global update
	rm -f ~/.config/valet/valet.sock
    valet install

alias php70="phpv php@7.0"
alias php71="phpv php@7.1"
alias php72="phpv php"

With this out of the way, you can easily switch to PHP 7.0 by executing php70 in your terminal. You can switch back to 7.2 by performing php72. The first time you switch to a particular PHP version might take a while. Subsequent switches will go much faster.

Credits for this phpv function go to my colleagues Seb and Willem. They created it based on this excellent blogpost on how to use multiple PHP versions in Mojave.

Stay up to date with all things Laravel, PHP, and JavaScript.

Follow me on Twitter. I regularly tweet out programming tips, and what I myself have learned in ongoing projects.

Every two weeks I send out a newsletter containing lots of interesting stuff for the modern PHP developer.

Expect quick tips & tricks, interesting tutorials, opinions and packages. Because I work with Laravel every day there is an emphasis on that framework.

Rest assured that I will only use your email address to send you the newsletter and will not use it for any other purposes.