How to auto format Blade Code in PHPStorm

In the world of web development, ensuring that your code is clean, tidy, and readable is an important part of the process. This is where code formatters like Prettier come into play. Prettier is an opinionated code formatter that supports many languages, and with the help of plugins, it can also format Laravel’s Blade templates.

You can also use PHPStorm’s built-in functions for formatting. In my testing, I have actually not found that much difference between PHPStorm’s Format on Save and running Prettier. They each have their pros and cons.

Built in pros

Prettier pros

Setup PHPStorm’s built in format on save

Reformat in PHPStorm

https://www.jetbrains.com/help/phpstorm/reformat-and-rearrange-code.html#reformat-on-save

Using Prettier in PHPStorm

To use Prettier, you need to install an npm module. First, install Prettier and either one of the Blade plugins. Navigate to your project directory in your terminal and run one of the following commands:

Alterantive 1: For Shuho’s plugin, run: https://github.com/shufo/prettier-plugin-blade

npm install --save-dev prettier @shufo/prettier-plugin-blade

Alternative 2: If you prefer the prettier-plugin-blade, run: https://www.npmjs.com/package/prettier-plugin-blade

npm install --save-dev prettier prettier-plugin-blade

I have found both of these to excellent and be very reliable, and I see no difference in their results.

Next, create a Prettier settings file:


{
  "plugins": [
    // Only one of these! 
    "@shufo/prettier-plugin-blade" <-- Alternative 1
    "./node_modules/prettier-plugin-blade/" <-- Alternative 2
  ],
  "overrides": [
    {
      "files": [
        "*.blade.php"
      ],
      "options": {
        "parser": "blade",
        "tabWidth": 4
      }
    }
  ]
}

To enable Prettier on save, go to Settings > Tools > Actions on Save > Run Prettier on Save.

Reformat in PHPStorm

Conclusion

I have found both PHPStorm’s built-in formatter and the Prettier plugins to be very reliable, with not too much difference between them. If you are working solo on many projects, I would recommend PHPStorm’s built-in reformatting. However, in a bigger team, you can utilise Prettier’s config files.