Automate code formatting in your Laravel project

Code style is important. Use this setup to automate it in your laravel project.
Ahmet Özışık · Founder · June 8th, 2021

This setup helps you even when team members don't use the same IDE. Now updated for Husky v6!

Install the dependencies

Let's pull in php-cs-fixer, husky and lint-staged to set this up.

composer require friendsofphp/php-cs-fixer --dev
npm i -D husky lint-staged

Create .php_cs in your project root

This file determines how to actually format your code. Here's a template for Laravel to get you started: Swiftmade's php-cs-fixer config for Laravel.

Also, don't forget to add .php_cs.cache to your gitignore file.

Set up husky & lint-staged to run php-cs-fixer

Husky allows us to execute commands before git commit runs, so that even if you forget to format your PHP files, they'll be formatted before the changes are committed. We'll create a git hook using husky, which will run lint-staged.

# Install husky
npm i -D husky

# Enable Git hooks
npx husky install

# To create Git hooks after install
npm set-script prepare "husky install"

# Add lint-staged as a pre-commit command
npx husky add .husky/pre-commit "npx lint-staged"

Lint-staged will grab the php files in the active changelist and pass them to php-cs-fixer. To achieve that, add this to your package.json:

"lint-staged": {
    "*.php": "php ./vendor/bin/php-cs-fixer fix --config .php_cs"

Wrap Up

In 3 simple steps, we've automated code styling. Automating code formatting in this way can be so much more productive as it lessens the burden of configuring each developer's machine individually. Plus, because you share your style file (.php_cs in this case) with the project, it's quite easy change your code-style and enforce those changes across your team instantly.

As a bonus, you can throw in .vue and .js into your lint-staged config and format them using a tool like prettier. Happy coding!

Complete monitoring toolkit for Laravel apps. Now in private beta!

Learn more