Automate Code Formatting with Laravel Pint during Git Commit

  • Share this:
Automate Code Formatting with Laravel Pint during Git Commit

To automatically format code using Laravel Pint during Git Commit, you can set up a pre-commit git hook in your Git repository that runs the Laravel Pint command to format your code before it is committed. This simple snippet ensures that your code is consistently formatted and adheres to the Laravel Pint coding standards, which can improve code readability and maintainability.

Also Read: Useful Github Repositories for Developers

Install Laravel Pint

composer require laravel/pint --dev

Automate Laravel Pint on Commits

Then, go to your root directory, find .git/hooks and create a copy of the pre-commit.sample hook file and make it executable using the following commands:

cp ./git/hooks/pre-commit.sample ./git/hooks/pre-commit
chmod +x ./git/hooks/pre-commit

Open that pre-commit file in your editor and paste the following bash script

files=$(git diff --cached --name-only --diff-filter=ACMR -- '*.php');
vendor/bin/pint $files
  • The files variable stores the list of PHP files that have been changed and are ready to be committed. 
  • The git diff command is used here to retrieve a list of changed files that are staged for commit. 
  • The --cached option specifies that only staged changes should be considered. 
  • The --name-only option is used to output only the file names, without any additional details. 
  • The --diff-filter=ACMR option limits the output to files that are Added, Copied, Renamed or Modified. 
  • The '--' argument is used to separate the options from the file pattern *.php, which specifies that only PHP files should be considered.
  • Then simply, the code runs the pint command on thees changed files on every Git commit.

Also Read: Laravel Responsables

In summary, this script retrieves the list of changed PHP files that are staged for commit and runs Laravel Pint on each file to automatically format it according to Laravel Pint standards before the changes are committed.

Also Read: Cool projects on Github

TWT Staff

TWT Staff

Writes about Programming, tech news, discuss programming topics for web developers (and Web designers), and talks about SEO tools and techniques