Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save vamuigua/b7d11fdd10ff3f49332a45f429e5459a to your computer and use it in GitHub Desktop.
Save vamuigua/b7d11fdd10ff3f49332a45f429e5459a to your computer and use it in GitHub Desktop.
Setup a custom pre-commit script for a Laravel Project

Setup a custom pre-commit script for a Laravel Project

Here's how you can set it up:

  1. First, make sure your pre-commit file is in the correct location. It should be in the .git/hooks/ directory of your project. If it's not there already, move it:
mv pre-commit .git/hooks/pre-commit
  1. Make sure the pre-commit file is executable:
chmod +x .git/hooks/pre-commit
  1. Open the pre-commit file and check its contents. It should contain bash script instructions that will run before each commit. A basic structure might look like this:
#!/bin/bash

echo "Running tests..."

cmd="php artisan test"

$cmd

status=$?

[ $status -eq 0 ] && echo "Tests passed" || exit

echo "Running style code fixer..."

cmd="./vendor/bin/pint"

$cmd

status=$?

[ $status -eq 0 ] && echo "Code fixing done!" || exit

cmd="./vendor/bin/phpstan analyse -c phpstan-pipelines.neon 
--memory-limit=2G"

$cmd

status=$?

[ $status -eq 0 ] && echo "php stan okay" || exit
  1. Customize the pre-commit file according to your needs. You might want to add Laravel-specific checks, such as:

    • Running PHP CodeSniffer
    • Executing PHPStan for static analysis
    • Running Laravel-specific test suites
  2. Test your pre-commit hook by making a commit

git add .
git commit -m "Test pre-commit hook"

If the pre-commit hook runs successfully and all checks pass, the commit will proceed. If any check fails, the commit will be aborted, and you'll need to fix the issues before committing again.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment