DEV Community

Cover image for VSCode for PHP and Laravel
Sean Kegel
Sean Kegel

Posted on • Updated on • Originally published at seankegel.com

VSCode for PHP and Laravel

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 Support

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.

Setup Intelephense Document Root and PHP 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"
},
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode
chmod a+x phpactor.phar # update permissions
mv phpactor.phar ~/.local/bin/phpactor # move file into path
Enter fullscreen mode Exit fullscreen mode
# Check the installation
phpactor status
Enter fullscreen mode Exit fullscreen mode

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 VSCode Plugin from VSIX

code --install-extension /path/to/phpactor.vsix
Enter fullscreen mode Exit fullscreen mode

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

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:

View Autocompletion

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” and popup appears to navigate directly to the welcome.blade.php file. The opt+; shortcut can also be used to navigate to the file.

Go 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"
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Once installed, the command palette (cmd+shift+p) can be opened and use the Prettier: Create Configuration File 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
Enter fullscreen mode Exit fullscreen mode
// .prettierrc
{
  "plugins": ["@shufo/prettier-plugin-blade"],
  "overrides": [
    {
      "files": ["*.blade.php"],
      "options": {
        "parser": "blade",
        "tabWidth": 4
      }
    }
  ]
}
Enter fullscreen mode Exit fullscreen mode

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
  }
}
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 comments 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

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.

"ide-helper": [
    "@php artisan ide-helper:generate",
    "@php artisan ide-helper:meta",
    "@php artisan ide-helper:models -N --reset"
]
Enter fullscreen mode Exit fullscreen mode

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"
]
Enter fullscreen mode Exit fullscreen mode

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, the 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"
    }
]
Enter fullscreen mode Exit fullscreen mode

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"
}
Enter fullscreen mode Exit fullscreen mode

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"
    }
}
Enter fullscreen mode Exit fullscreen mode

Top comments (12)

Collapse
 
cwprogram profile image
Chris White

I really enjoyed the effort put into this article. Actually quite impressed at the level of code completion offered through the various plugins. The examples were laid out nicely and I appreciate seeing a full settings file available at the end. Thanks for the great article!

Collapse
 
msamgan profile image
Mohammed Samgan Khan

I agree for most of the part but if you are using laravel, instead of using Prettier you should use laravel pint. Here is a way you can use laravel pint in your vscode setup
codebysamgan.com/how-to-add-larave.... Moreover I also created an extension for the same purpose, you should check out.
marketplace.visualstudio.com/items...

Collapse
 
sean_kegel profile image
Sean Kegel

I use both Prettier and Pint. I use Prettier for formatting frontend code like React/Vue. However, I also use it for Blade templates since Pint does not format Blade templates.

Prettier can also sort Tailwind classes as well which I prefer.

All my normal PHP files are formatted with Pint, Prettier does not touch those.

Collapse
 
msamgan profile image
Mohammed Samgan Khan

yes combining them together is a great idea. I do the same.

Collapse
 
sergunik profile image
Serhii

Maybe I’m blind but can you explain specifically for me - WHY?
PHPStorm is perfect IDE for it. Why need to invent bicycle and try to setup the rest of tools for it?

Collapse
 
sean_kegel profile image
Sean Kegel

PhpStorm is fantastic and if you have the money or your company provides it, than definitely, you should be using it. It is what I personally use for PHP development. However, there are many people that use VSCode for a lot more than PHP and are comfortable in that environment. So I hope this article can help them.

Collapse
 
msamgan profile image
Mohammed Samgan Khan

very few people know about this but JetBrains also provides open-source licenses, If you work on any open-source project you can apply for this, here is the link jetbrains.com/community/opensource...

Collapse
 
jagdishjp profile image
Jagdish Patel

Because PHPStorm is charging you good amount of money for the features which are easily available in VSCode free of cost.

Collapse
 
sergunik profile image
Serhii • Edited

I'll respond you in BDD style))
Given enough engineering skills
When I'm as a Software Engineer want to have a well-paid job (have a payment for my engineering stuff)
And have updates to software tools that I use
Then I need to pay for software tools that I use
And pay for movies, music, news, etc.

Does it makes sense?

Thread Thread
 
drsimplegraffiti profile image
Abayomi Ogunnusi

Nice article

Collapse
 
shjordan profile image
Jordan Humberto de Souza

You should give Laravel Pint a try.

Collapse
 
shjordan profile image
Jordan Humberto de Souza

You should give Laravel Pint a try