Switching PHP versions automatically with Laravel Valet v4

·
11th August 2023
·
2 minute read

This article is an update of the original for Valet v2 and v3: Switching PHP versions automatically with Laravel Valet.

I previously contributed to the Laravel Valet project in 2021 adding the ability to switch PHP versions using a .valetphprc file saved in the root of a project which has become a useful feature used by developers in projects run within Valet.

Since then Laravel Valet has expanded to include the new isolate command and expanded the (now renamed) .valetrc file which has a slightly different format, so below is the updated script for zsh to allow you to switch PHP versions automatically when traversing your project directories.

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

# Auto switch PHP versions using valet
autoload -U add-zsh-hook
load-valetrc() {
  # Check if there is a .valetrc or .valetphprc in the folder and set path to it
  if [[ -a .valetrc ]]; then
    local valetrc_path=".valetrc"
  elif [[ -a .valetphprc ]]; then
    local valetrc_path=".valetphprc"
  else
    # No files found
    return
  fi

  # Get contents of file
  local valetrc_version="$(cat "${valetrc_path}")"

  # Remove leading and trailing whitespace
  valetrc_version=${valetrc_version##[[:space:]]}
  valetrc_version=${valetrc_version%%[[:space:]]}

  # Extract the valet php string from the file
  if [[ $valetrc_version == *php@* ]]; then
    valetrc_version=${valetrc_version#*php@}
    valetrc_version=${valetrc_version%%[[:space:]]*}

    local current_php_version=$(php -r "echo PHP_MAJOR_VERSION . '.' . PHP_MINOR_VERSION;")

    if [ "php@$current_php_version" != "$valetrc_version" ]; then
      valet use
    fi
  fi
}
add-zsh-hook chpwd load-valetrc

Now when you cd into your project directory, if a .valetrc or .valetphprc file with a valid version of PHP is found (e.g. php=php@8.2 or php@8.2) 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.