- read

VSCode for PHP and Laravel

Sean Kegel 59

VSCode + PHP + Laravel

This post should help you setup Visual Studio Code to use for PHP and Laravel development. It it a solid base configuration that can be expanded upon using additional workspace specific configurations. I will cover the best extensions to use as well as some helpful configuration settings and external tools.

Let’s get started with the most important extensions!

Intelephense

This is the most important extension to install for PHP support. It provides a fast language server that adds code completion, go to definition, formatting, and more. You can also purchase a license at Intelephense, which I highly recommend. It adds some additional features like renaming symbols and other code actions.

Once installed, disable the built-in PHP features so Intelephense is used instead:

Disable built-in PHP settings
Disable built-in PHP settings

If a license was purchased, use cmd+shift+p to bring up the Command Palette and search for “Enter licence key”.

For the most part, the default settings are fine for Intelephense. At a workspace level, setting the document path and PHP version can be helpful if working on multiple PHP projects and frameworks.

Configure PHP Document Root and Version
Configure PHP Document Root and Version

Finally, if Intelephense will be used for formatting (versus an external tool like PHP CS Fixer or Pint), then set it as the default formatter for PHP files. This is done by pulling up the JSON version of the settings.

"[php]": {
"editor.defaultFormatter": "bmewburn.vscode-intelephense-client"
}

Phpactor

This is both an external tool and an extension. However, the extension is not available in the VSCode extension marketplace and needs to be installed manually. The extension provides a lot more helpful code actions like replacing a qualifier with an import and adding return types.

First, install Phpactor by using the instructions or following the steps below:

# Download phpactor.phar
curl -Lo phpactor.phar https://github.com/phpactor/phpactor/releases/latest/download/phpactor.phar
chmod a+x phpactor.phar # update permissions
mv phpactor.phar ~/.local/bin/phpactor # move file into path
# Check the installation
phpactor status

With Phpactor installed on the system, next is to install the plugin. Download the latest release (phpactor.vsix). Then install in VSCode either by importing the plugin or using the CLI.

Install external VSCode extension
Install external VSCode extension
code --install-extension /path/to/phpactor.vsix

With the plugin installed, Phpactor will index the workspace and then add new code actions. The screenshots below show replacing a qualifier with a namespace and adding return types.

Replace qualifier with import
Replace qualifier with import
Add missing return types
Add missing return types

Laravel Extra Intellisense

This plugin adds additional autocompletion for things like views and routes. For example, in the routes/web.php file, a list of available views displays in the autocompletion popup:

Autocompletion for views
Autocompletion for views

It also adds autocompletion for Laravel validation rules and configuration.

Laravel Goto

This plugin is used to quickly navigate to view, config, and other files in a Laravel application just be hovering over the string. For example, in the routes/web.php file again, when hovering over “welcome” a popup appears to navigate directly to the welcome.blade.php file. The opt+; shortcut can also be used to navigate to the file.

Navigate to view file
Navigate to view file

Laravel Blade Snippets

This plugin adds syntax highlight for .blade.php files as well as helpful snippets. It can even be used to format Blade files if desired. However, later in this post, Prettier will be setup to format Blade files.

Better Pest / Better PHPUnit

These plugins provide easy keybindings for running tests. If the project uses Pest, use the Better Pest extension, otherwise, use Better PHPUnit. These plugins can also be enabled/disabled specifically for workspaces as well if using multiple projects.

The following keybindings are provided by default to run a specific test depending on the cursor location, or run all the tests in the file, or the previously run test(s).

{
"key": "cmd+k cmd+r",
"command": "better-pest.run"
},
{
"key": "cmd+k cmd+f",
"command": "better-pest.run-file"
},
{
"key": "cmd+k cmd+p",
"command": "better-pest.run-previous"
}

Refer to the docs for additional settings to setup with Docker or other more advanced configurations.

Prettier

Prettier is an opinionated framework for formatting JavaScript/TypeScript files. It is highly recommended for formatting React and Vue files if using something like Inertia. It can also format other filetypes, like JSON and Markdown. After installing the extension, also install Prettier into the project:

npm install — save-dev — save-exact prettier

Once installed, the command palette (cmd+shift+p) can be opened and use the “Prettier: Create Configuration File” command to create a .prettierrc file in the project. See the following for a list of configurable rules: Options · Prettier.

Additional plugins can be added to support more features and languages for Prettier as well, such as Blade support. Install the shufo/prettier-plugin-blade plugin and add it to the config file:

npm install — save-dev @shufo/prettier-plugin-blade prettier
// .prettierrc
{
"plugins": ["@shufo/prettier-plugin-blade"],
"overrides": [
{
"files": ["*.blade.php"],
"options": {
"parser": "blade",
"tabWidth": 4
}
}
]
}

It can even sort Tailwind CSS classes in Blade files by using the sortTailwindcssClasses option. Look at the Github repo for additional settings.

To set the Prettier as the default formatter for various file types, use the following settings in VSCode:

{
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[svelte]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[blade]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
}
}

Laravel IDE Helper

Though this is not an extension for VSCode, the Laravel IDE Helper greatly improves the development experience in the editor. It generates helper files for Laravel applications to have better autocompletion support for various magic methods in Laravel that Intelephense cannot resolve. It can analyze models, migrations, facades, and more. Install it with composer.

composer require — dev barryvdh/laravel-ide-helper

Once installed, new Artisan commands are available to generate the helper files. The following are the most useful.

php artisan ide-helper:generate # Generate PHPDocs for facades
php artisan ide-helper:meta # Generate meta file to add support for the factory pattern
php artisan ide-helper:models # Generate PHPDocs for models

For the models generation, it is possible to add PHPDocs directly to the model files or use an external file. The former tends to be more accurate but adds a lot of doc blocks to the files. The latter is cleaner but sometimes go to definition goes to the generated file versus the actual model. Decide what works best for the project.

When the commands are run, VSCode can now autocomplete fields on models, like the email field on the User model below.

Autocompletion for model properties
Autocompletion for model properties

This can be made even simpler by adding some scripts to the composer.json file. First, create an ide-helper script to run the various commands. The script below writes the PHPDocs externally for the models versus on the models themselves.

"scripts": {
...
"ide-helper": [
"@php artisan ide-helper:generate",
"@php artisan ide-helper:meta",
"@php artisan ide-helper:models -N --reset"
]
}

Next, update the post-update-cmd script. This will automatically run the ide-helper script when running composer update.

"post-update-cmd": [
"@php artisan vendor:publish --tag=laravel-assets --ansi --force",
"Illuminate\\Foundation\\ComposerScripts::postUpdate",
"@composer ide-helper"
]

To take this one step further, VSCode tasks can be configured to run this command from within VSCode and even assign it to a shortcut.

To create the tasks.json file, use cmd+shift+p to open the command palette and search for “Tasks: Configure Task”. Inside the menu select the “Create tasks.json file from template”, then select “Others”. This creates a tasks.json file inside the .vscode directory in the project. In the tasks.json file, add the following:

“tasks”: [
{
“label”: “Laravel IDE Helper”,
“type”: “shell”,
“command”: “composer ide-helper”
}
]

Now this command can be run from the command palette by going to “Tasks: Run Task”.

Finally, to add a keyboard shortcut for the tasks, add the following to the keybindings.json:

{
"key": "cmd+shift+.",
"command": "workbench.action.tasks.runTask",
"args": "Laravel IDE Helper"
}

Now clicking cmd+shift+. will quickly run the IDE helper.

Other Helpful Extensions

Conclusion

I hope this guide will help make you a much more efficient Laravel developer. Visual Studio Code is a powerful editor and with the right extensions and configuration is an excellent editor for PHP and Laravel development.

It is not quite as powerful as PhpStorm (especially with the Laravel Idea package) and requires more work to configure. However, for a free to use editor, it is tough to beat. Though I highly recommend PhpStorm, I know a lot of developers have experience with VSCode and maybe doing more than just PHP development so the change it not worth it.

Please let me know in the comments if there’s anything else you would like me to cover or expand on, like Laravel Sail support or additional tools like Phpstan/Larastan. Also, let me know if there’s any other helpful extensions or configurations I might have missed.

Finally, below I provided an example of the settings I use in VSCode.

Settings

Here’s an example of the settings I use in VSCode for PHP and Laravel development. I also make heavy use of workspace specific settings to further customize my setup for individual projects.

{
"files.autoSave": "onFocusChange",
"files.defaultLanguage": "markdown",
"files.encoding": "utf8",
"files.eol": "\n",
"files.insertFinalNewline": true,
"files.trimFinalNewlines": true,
"files.trimTrailingWhitespace": true,


// ********************
// Formatting
// ********************
"prettier.endOfLine": "lf",


// ********************
// Language Settings
// ********************

// JavaScript/TypeScript
"javascript.preferences.quoteStyle": "single",
"typescript.preferences.quoteStyle": "single",
"typescript.updateImportsOnFileMove.enabled": "always",
"javascript.updateImportsOnFileMove.enabled": "always",
"javascript.preferences.importModuleSpecifier": "relative",
"typescript.preferences.importModuleSpecifier": "relative",
"[javascript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[javascriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescript]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[typescriptreact]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[svelte]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[vue]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},

// CSS
"tailwindCSS.emmetCompletions": true,
"tailwindCSS.includeLanguages": {
"Typescript": "typescriptreact"
},

// PHP
"php.validate.enable": false,
"php.suggest.basic": false,
"[php]": {
"editor.defaultFormatter": "bmewburn.vscode-intelephense-client"
},
"[blade]": {
"editor.autoClosingBrackets": "always",
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"intelephense.telemetry.enabled": false,

// JSON
"[json]": {
"editor.defaultFormatter": "esbenp.prettier-vscode",
"editor.formatOnSave": true
},
"[jsonc]": {
"editor.defaultFormatter": "esbenp.prettier-vscode"
}
}

Thank you for reading until the end. Please consider following the writer and this publication. Visit Stackademic to find out more about how we are democratizing free programming education around the world.