Setup Laravel Pint Pre-Commit Hooks
Laravel Pint is an opinionated PHP code style fixer, built on top of PHP-CS-Fixer. It offers a good base line of cleaning up the formatting of your code to make it look more consistent.
By default you could run ./vendor/bin/pint
on your project and clean everything all at once. But if you’re working with a team or on a large project this would create a major diff change and might scare some team members. The best way to roll out Laravel Pint to a team is to run it incrementally on your staged files with a pre-commit
hook.
Husky is a tool that allows you to setup commit hooks in your project. It can rewrite commits, run linters, run testing suites, or anything you want in your code base using the git hooks. We will be using husky in conjunction with lint-staged which allows you to run commands only on your staged commit files.
Setup
Install Laravel Pint in your project
composer require laravel/pint --dev
Install Husky and lint-staged NPM packages
npm install --save-dev husky lint-staged
Enable Git Hooks with Husky
npx husky install
Add lint-staged as a pre-commit hook in husky
npx husky add .husky/pre-commit 'lint-staged'
Add the lint-staged lines to your package.json
{
"scripts": {
"prepare": "husky install"
},
"lint-staged": {
"**/*.php": "./vendor/bin/pint --preset laravel"
},
"devDependencies": {
"husky": "^8.0.0",
"lint-staged": "^13.0.3"
}
}
Make a change to one of your PHP files, stage and commit it. After it is committed you should see that the PHP file should be linted with Pint.