Switching PHP versions automatically with Laravel Valet

·
29th August 2021
·
1 minute read

2023-08-11: There is a newer version of this article that covers the latest version of Laravel Valet

I recently made a contribution to Laravel Valet which adds the ability to specify the PHP version via a .valetphprc file in the project root to make it easier working with the different versions of PHP that some projects may use.

Just make sure you're using Laravel Valet v2.16.0 or higher on macOS and then add this simple script in your ~/.zshrc file:

autoload -U add-zsh-hook
load-valetphprc() {
  [[ -a .valetphprc ]] || return
  local php_version=$(php -r "echo PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION;")
  local valetphprc_path=".valetphprc"

  if [ -f "$valetphprc_path" ]; then
    local valetphprc_version="$(cat "${valetphprc_path}")"

    if [ "php@$php_version" != "$valetphprc_version" ]; then
      valet use
    fi
  fi
}
add-zsh-hook chpwd load-valetphprc

Now when you cd into your project directory, if a .valetphprc file with a valid version of PHP is found (e.g. php@7.4) the valet use command will be run automatically giving you one less thing to think about when working across multiple projects.

0 Comments

Be the first to leave a comment!

Leave a comment

Your email address will not be published. Required fields are marked with *

As a privacy-first company we won't collect your IP address, browser user agent, or HTTP referrer header while you're on our website. When you submit a comment your name and email address will be checked using the Akismet spam filtering service but is not used for any other purpose. Find out more about how we protect your privacy.