Skip to content
Arie Visser

    Arie Visser ·

    Guardrails for AI-Assisted Development in Laravel

    Why guardrails?

    Guardrails have always been an important aspect of software engineering.

    At the beginning of my career, I was fully focused on developing new features and fixing bugs. But when a new senior joined the team, they did not start by developing new features as fast as possible. They first spent most of their time on improving the tools we could use as a team, such as improving the CI pipeline and introducing code quality tools.

    I think focusing on these tools and guardrails has become even more important since the introduction of AI-powered coding. This might even distinguish seasoned developers who were used to writing code by hand and have a complete mental model of a codebase from creators who are not used to writing code.

    In most cases, building features themselves is not that hard anymore with the help of AI coding tools. At the same time, the importance of security and quality has increased.

    Since this blog is mainly about Laravel, I will give some examples of guardrails you can create for your PHP / Laravel projects. I use Claude Code as my AI coding tool, but there are comparable tools for other frameworks and AI assistants.

    Claude Code hooks

    I like to review the code that is created by AI tools before it is committed and pushed. This way, it is easier for me to improve the code, and be part of the creation process. After a task is finished, I want to be sure the quality tools that are used in a project (such as unit tests) are executed.

    Instructions like these that are written in CLAUDE.md can be ignored. Hooks run automatically. You can register them in .claude/settings.json:

    {
      "hooks": {
        "PreToolUse": [
          {
            "matcher": "Bash",
            "hooks": [
              {
                "type": "command",
                "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/guard-bash.sh"
              }
            ]
          }
        ],
        "PostToolUse": [
          {
            "matcher": "Edit|Write",
            "hooks": [
              {
                "type": "command",
                "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-php.sh"
              }
            ]
          }
        ],
        "Stop": [
          {
            "hooks": [
              {
                "type": "command",
                "command": "\"$CLAUDE_PROJECT_DIR\"/.claude/hooks/check-tests.sh"
              }
            ]
          }
        ]
      }
    }

    Make the scripts executable with chmod +x. They use jq to read the hook input.

    Prevent git push and production access

    With exit code 2 the command is blocked, and the error message is sent to Claude. Other non-zero exit codes do not block anything.

    #!/usr/bin/env bash
    # .claude/hooks/guard-bash.sh
    
    block() {
      echo "Blocked: $1" >&2
      exit 2
    }
    
    command=$(jq -er '.tool_input.command') || block 'could not read the command.'
    
    if grep -qE 'git +(-[^ ]+ +([^ -][^ ]* +)?)*push' <<< "$command"; then
      block 'pushing is done by a human.'
    fi
    
    # Replace with your own hosts and environment files.
    if grep -qiE '\.prod\.example\.com|\.env\.production|--env[= ]production' <<< "$command"; then
      block 'no access to production services.'
    fi

    Of course, this is not a watertight security boundary, but it is a fast and simple solution.

    You can also resolve this at the infrastructure level. Keep production credentials off your development machine, protect your branches, and use sandboxing to restrict network access.

    Run quality tools after changes

    A PostToolUse hook cannot undo edits, but with exit code 2 Claude sees the errors and can fix them.

    #!/usr/bin/env bash
    # .claude/hooks/check-php.sh
    
    file=$(jq -er '.tool_input.file_path') || exit 2
    [[ $file == *.php && -f $file ]] || exit 0
    cd "$CLAUDE_PROJECT_DIR" || exit 2
    
    check() {
      output=$("$@" 2>&1) || { echo "$output" >&2; exit 2; }
    }
    
    check vendor/bin/rector process "$file" --no-progress-bar
    check vendor/bin/ecs check "$file" --fix --no-progress-bar
    check vendor/bin/phpstan analyse "$file" --no-progress

    Run tests before finishing a task

    A Stop hook runs when Claude wants to finish a task. With exit code 2 it sees the failing tests and it will try to fix them.

    #!/usr/bin/env bash
    # .claude/hooks/check-tests.sh
    
    # Already continuing because of this hook: prevent an endless loop.
    [[ $(jq -r '.stop_hook_active') == true ]] && exit 0
    
    cd "$CLAUDE_PROJECT_DIR" || exit 2
    
    # Skip when there are no uncommitted PHP changes.
    [[ -n $(git status --porcelain -- '*.php') ]] || exit 0
    
    # You can run your E2E tests here as well.
    output=$(vendor/bin/phpunit --no-progress 2>&1) || { echo "$output" >&2; exit 2; }

    PHPStan

    Since PHP is dynamically typed, PHPStan helps to find type errors, undefined methods, and null issues without running the code. Larastan adds support for Laravel.

    vendor/bin/phpstan analyse app --level=8

    You can use a baseline for existing errors, or ask an agent to fix them. This is typically a task for LLMs. But check that the agent really fixes the errors, instead of adding them to the baseline, ignoring them, or loosening types.

    Rector

    Rector automates refactoring: upgrades, type declarations, and dead code removal. There are rule sets for Laravel as well.

    vendor/bin/rector process app --dry-run

    You can use Rector to upgrade codebases (even from PHP 5.3 to PHP 8.6), but you can also run it purely as a quality tool during development.

    Easy Coding Standard (ECS)

    ECS combines PHP_CodeSniffer and PHP-CS-Fixer in one config, so you can make sure the style of the code follows a certain set of rules.

    vendor/bin/ecs check --fix

    Unit tests with PHPUnit

    Static analysis does not know what your code should do. Write or review the test yourself, and let the agent write the implementation:

    #[Test]
    public function it_calculates_the_total_with_vat(): void
    {
        $total = (new VatCalculator())->total(amount: 100, rate: 0.21);
    
        $this->assertEqualsWithDelta(121.0, $total, 0.001);
    }

    Make sure to look critically at the tests, since an agent might just try to mirror the behavior of the code.

    E2E tests with Behat or Playwright

    I think after the introduction of AI coding tools, end-to-end tests are the most important. They describe what should be built, and how your application looks from a user perspective.

    With Behat you describe the behavior of an application in readable scenarios:

    Scenario: Paying an open invoice
      Given I have an open invoice
      When I pay the invoice
      Then the invoice should be marked as paid

    You might also decide to use Playwright. This makes it easier to test JavaScript.

    test('pays an open invoice', async ({ page }) => {
      await page.goto('/invoices/1');
      await page.getByRole('button', { name: 'Pay' }).click();
      await expect(page.getByText('Paid')).toBeVisible();
    });

    Where to run what?

    This might depend on the kind of project you are working on. For most of my projects, this works best:

    • After each edit: Rector, ECS, and PHPStan on the changed file
    • Before finishing a task: PHPUnit
    • In CI: everything, including E2E tests, with Rector in --dry-run mode and ECS without --fix

    Hooks give the agent fast feedback, and running guardrails locally finds issues fast, but you always need CI as the final guard.

    The code samples in this post were made with Claude Code.