Consent

This site uses third party services that need your consent.

Skip to content
Steven Roland
  • Automatically Run Laravel Pint with Git Pre-Commit Hook

    Keeping coding standards in you projects is a great practice, but it can be tricky to introduce and then maintain. That becomes an even harder task when multiple team members are involved. That's why I've set up some basic, easy-to-use, and super helpful tooling for almost every project I've worked on since Laravel Pint was introduced.

    Laravel Pint is an opinionated PHP code style fixer for Laravel projects, built on top of PHP-CS-Fixer. It's used to clean up the formatting of your code to make it look more consistent.

    After installing it, running ./vendor/bin/pint on your project will get you going and clean everything all at once. Depending on the size of your project, this can produce a huge diff to sort out, and if you're working with a team that has multiple tasks in motion, things can get even more complicated from there.

    I think he best way to roll out Laravel Pint to a team is to run it incrementally, and automatically on your staged files via git's pre-commit hook. That's where Husky comes in.

    Husky is a tool that allows you to setup commit hooks in your project. It can rewrite git commits, run code linters, run testing suites, or really anything you want in your code base using the git hooks. In this case, we want to use husky with a package called lint-staged which allows you to run commands only on your staged commit files. Let's get to it:

    1. Use Composer to install Pint in you Laravel project

    composer require laravel/pint --dev

    2. Use NPM to install Husky and lint-staged

    npm install --save-dev husky lint-staged

    3. Get Husky setup to use Git hooks

    npx husky init

    NOTE: Before Husky version 9, you may need to run npx husky install instead.

    4. Add lint-staged to Husky's configuration

    npx husky add .husky/pre-commit 'lint-staged'

    5. Add the lint-staged object to your package.json file. I also like to add the "prepare": "husky install" script to the scripts object.

    {
         "scripts": {
            "prepare": "husky install"
         },
         "lint-staged": {
             "**/*.php": "./vendor/bin/pint --preset laravel"
         }
     }

    Now anytime you or a team member makes a change to any PHP files, Husky will catch it, fix anything that doesn't fit, and everyone on your team can go about their day.

    More posts

    Keyboard Shortcuts with Alpine.js

    Use Alpine.js to quickly, and very easily, implement key bindings into your website. I wrote an example to build a simple search component.