loading...

★ Easily switch PHP versions in Laravel Valet

freekmurze profile image Freek Van der Herten Originally published at freek.dev on ・2 min 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.

Discussion

pic
Editor guide