Automate code formatting in your Laravel project

Code style is important. Use this setup to automate it in your laravel project.
Ahmet Özışık · Swiftmade's Founder · 17 Apr, 2020

This setup helps you even when team members don't use the same IDE.

1. 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 husky lint-staged --save-dev

2. 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.

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

Husky allows us to execute commands before git commit runs. And we'll use lint-staged to actually run that command on the current changelist, rather than the entire project.

To configure these useful packages, we'll head to our package.json file and add these lines:

"husky": {
    "hooks": {
        "pre-commit": "lint-staged"
"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.

More From Swiftmade

Nov 22
Labkar Case Study
Mar 5
Blogdown v2 Released
Apr 10
Passing user input to orderBy is recipe for SQL injection