Skip to content

Posts › Development

Development

Where should this rule live? Claude Code hooks in a Laravel app

A line in CLAUDE.md is advice that Claude follows most of the time. A hook is a script that runs every time. Five hooks for a Laravel app (Pint, migrations, destructive Artisan commands, Pest, session context), written partly as Artisan commands, and for each one the other places the same rule could live.

21 min read

My CLAUDE.md says "run Pint on every PHP file you change". Claude follows it most of the time. Then, in a long session, after a context compaction or a change of direction, a badly formatted file ends up in a commit, and I notice it in review.

That is how instructions work: they are advice, and the model weighs them against everything else in its context. Claude Code has a second mechanism, hooks: shell commands that the harness runs at fixed points of the session, whatever the model decides. A hook is a guarantee.

Guarantees have a cost, though, and some rules are better served elsewhere: in a permission rule, in a git hook, in CI. In this article I write five hooks for a Laravel app, and for each one I look at where else the same rule could live and when that place is better. Every example was run against a fresh Laravel 13.37 app with Claude Code 2.1.301, and the behaviours I describe are the ones I observed.

How a hook works

A hook is an entry in a settings file that says: when this event happens, for these tools, run this command. The file that matters for a team is .claude/settings.json in the project root, which you commit. .claude/settings.local.json is the gitignored personal variant, and ~/.claude/settings.json applies to all your projects.

Claude Code has more than thirty events. These are the ones that come up in this article:

Event When it fires What a hook can do
SessionStart a session starts, resumes, or is compacted add context for Claude
PreToolUse before a tool runs allow, deny, or ask the user; change the input
PostToolUse after a tool succeeds react to the result, give Claude feedback
Stop Claude is about to end its turn send it back to work
UserPromptSubmit you send a prompt add context, or block the prompt

The command receives a JSON payload on stdin. For an edit, the interesting part looks like this:

json
 1{
 2  "hook_event_name": "PreToolUse",
 3  "tool_name": "Edit",
 4  "tool_input": {
 5    "file_path": "/home/me/app/database/migrations/0001_01_01_000000_create_users_table.php",
 6    "old_string": "...",
 7    "new_string": "..."
 8  }
 9}

The command answers in one of two ways. With exit codes: 0 means go ahead, 2 means block, and whatever the script wrote on stderr is sent to Claude as the reason. Or with a JSON object on stdout, which allows finer decisions, such as denying a tool call with an explanation, or adding text to Claude's context. Any other exit code is treated as a hook error and the action proceeds.

Hooks as Artisan commands

Hooks are usually written in Bash with jq. That is fine for a one-liner, and I use Bash for the two simplest hooks below. However, as soon as a rule needs to know something about the application (which migrations have run, which database .env points to), Bash has to reimplement Laravel badly. An Artisan command has the container, the config and the database already available, and it can be tested with Pest.

The hook payload handling is the same for every command, so it goes in a small abstract class:

php
 1<?php
 2
 3namespace App\Console\Commands\Agent;
 4
 5use Illuminate\Console\Command;
 6
 7abstract class HookCommand extends Command
 8{
 9    private static ?array $fake = null;
10
11    protected array $payload = [];
12
13    abstract protected function handleHook(): int;
14
15    public function handle(): int
16    {
17        $this->payload = self::$fake
18            ?? json_decode(stream_get_contents(STDIN) ?: '{}', true)
19            ?? [];
20
21        return $this->handleHook();
22    }
23
24    public static function fake(?array $payload): void
25    {
26        self::$fake = $payload;
27    }
28
29    protected function payload(string $key, mixed $default = null): mixed
30    {
31        return data_get($this->payload, $key, $default);
32    }
33
34    protected function deny(string $reason): int
35    {
36        return $this->respond(['hookSpecificOutput' => [
37            'hookEventName' => 'PreToolUse',
38            'permissionDecision' => 'deny',
39            'permissionDecisionReason' => $reason,
40        ]]);
41    }
42
43    protected function addContext(string $context): int
44    {
45        return $this->respond(['hookSpecificOutput' => [
46            'hookEventName' => $this->payload('hook_event_name'),
47            'additionalContext' => $context,
48        ]]);
49    }
50
51    private function respond(array $response): int
52    {
53        $this->line(json_encode($response, JSON_UNESCAPED_SLASHES));
54
55        return self::SUCCESS;
56    }
57}

The commands answer only through JSON on stdout and always exit with 0. That keeps them easy to test, because $this->artisan() captures stdout, and the static fake() replaces stdin in tests.

The price is the framework boot. On my machine (PHP 8.5, no OPcache for the CLI) one of these commands takes about 150 ms, against about 5 ms for a Bash script that exits early. On a PreToolUse hook for edits, that adds 150 ms to each edit, which in practice is invisible next to the time the model takes to write the edit. On a hook that fires dozens of times per turn, it starts to add up, so I keep Artisan for the hooks that actually need the application.

I have since turned this class into a package, laravel-claude-hooks. It adds a typed input for each event, registration through a #[ClaudeHook] attribute, an install command that keeps .claude/settings.json in sync with your commands, testing helpers, an http transport for frequent hooks, and the five hooks of this article ready to enable. The code in this article uses the plain class, so you can follow it with or without the package.

Formatting with Pint

The first hook replaces the line in CLAUDE.md. After every Edit or Write on a PHP file, it runs Pint on that file:

bash
 1#!/usr/bin/env bash
 2file=$(jq -r '.tool_input.file_path // empty')
 3
 4[[ "$file" == *.php ]] || exit 0
 5
 6"$CLAUDE_PROJECT_DIR"/vendor/bin/pint --quiet "$file"
json
 1{
 2  "hooks": {
 3    "PostToolUse": [
 4      {
 5        "matcher": "Edit|Write",
 6        "hooks": [
 7          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pint.sh\"" }
 8        ]
 9      }
10    ]
11  }
12}

matcher is matched against the tool name, and $CLAUDE_PROJECT_DIR points to the project root, so the hook works whatever directory Claude has moved to. The script takes about 200 ms when it formats a file.

When I asked Claude to write a deliberately messy class and then add a method to it, the file on disk ended up formatted. There is one side effect: Claude Code notices that the file changed after the write and Claude reads it again before the next edit. One extra Read per formatted file is the cost of this hook.

Where else this rule could live.

  • CLAUDE.md: costs nothing and works most of the time. If an occasional unformatted file is acceptable, it is enough.
  • A git pre-commit hook (CaptainHook, GrumPHP, or a plain .git/hooks/pre-commit): formats at commit time for everybody, humans included. It complements the Claude hook well, since the agent hook keeps the files clean during the session, which keeps diffs readable while you review them.
  • CI: pint --test in a workflow is the final check. It catches everything, but late, after the push.
  • A different hook event: PostToolBatch runs once after a batch of tool calls. With many parallel edits, it formats once per batch.

My choice is the hook during the session plus pint --test in CI. The pre-commit hook becomes redundant at that point.

Protecting migrations that already ran

Some files should never be touched by Claude. For most of them a hook is overkill, because Claude Code has permission rules:

json
 1{
 2  "permissions": {
 3    "deny": [
 4      "Read(./.env)",
 5      "Edit(./.env)",
 6      "Edit(./composer.lock)"
 7    ]
 8  }
 9}

With these rules, a Read on .env fails with a permission error, and so does an Edit on composer.lock. No script, no boot time. For a fixed list of paths, a deny rule is the right place.

Migrations are different. Editing a migration is fine until it has run, and after that it is almost always a mistake: the change never reaches the existing databases, and the fix is a new migration. A deny rule cannot express "has already run", because the answer is in the migrations table. An Artisan command can read it:

php
 1<?php
 2
 3namespace App\Console\Commands\Agent;
 4
 5use Illuminate\Support\Facades\DB;
 6use Illuminate\Support\Str;
 7
 8class GuardMigrations extends HookCommand
 9{
10    protected $signature = 'agent:guard-migrations';
11
12    protected $description = 'PreToolUse hook: deny edits to migrations that already ran';
13
14    protected function handleHook(): int
15    {
16        $path = (string) $this->payload('tool_input.file_path');
17
18        if (! Str::startsWith($path, database_path('migrations'))) {
19            return self::SUCCESS;
20        }
21
22        $migration = basename($path, '.php');
23
24        if (DB::table('migrations')->where('migration', $migration)->doesntExist()) {
25            return self::SUCCESS;
26        }
27
28        return $this->deny(
29            "{$migration} has already run on this database. Create a new migration instead of editing it."
30        );
31    }
32}
json
 1{
 2  "matcher": "Edit|Write",
 3  "hooks": [
 4    { "type": "command", "command": "php \"$CLAUDE_PROJECT_DIR/artisan\" agent:guard-migrations" }
 5  ]
 6}

Returning without output means "no opinion": the normal permission flow continues. When the command denies, the reason goes back to Claude, and the wording matters, because Claude acts on it. I asked Claude to add a column by editing create_users_table directly. The edit was denied, Claude reported the reason, and it proposed a new add_nickname_to_users_table migration, while asking me how to proceed, since I had explicitly asked for a direct edit.

Since it is an Artisan command, testing it is ordinary Pest. RefreshDatabase runs the migrations, so the users table migration is recorded as run:

php
 1<?php
 2
 3use App\Console\Commands\Agent\HookCommand;
 4use Illuminate\Foundation\Testing\RefreshDatabase;
 5
 6uses(RefreshDatabase::class);
 7
 8afterEach(fn () => HookCommand::fake(null));
 9
10it('denies edits to a migration that already ran', function () {
11    HookCommand::fake(['tool_input' => [
12        'file_path' => database_path('migrations/0001_01_01_000000_create_users_table.php'),
13    ]]);
14
15    $this->artisan('agent:guard-migrations')
16        ->expectsOutputToContain('"permissionDecision":"deny"')
17        ->assertSuccessful();
18});
19
20it('lets Claude edit a migration that has not run yet', function () {
21    HookCommand::fake(['tool_input' => [
22        'file_path' => database_path('migrations/2026_10_20_000000_create_orders_table.php'),
23    ]]);
24
25    $this->artisan('agent:guard-migrations')
26        ->doesntExpectOutputToContain('deny')
27        ->assertSuccessful();
28});

The hook has one hole. It watches the Edit and Write tools, so a sed -i on the same file through Bash goes around it. In my test Claude stated that it had not tried that route, which is reassuring, but it is the model's choice. If that matters to you, add a Bash matcher that looks for migration paths in the command.

Where else this rule could live.

  • A deny rule on database/migrations/**: blocks every migration, including the one Claude has just created and still needs to fix. Too coarse.
  • Git: "protected once it is on main" is a reasonable rule for a team, and it does not need a database. The check becomes git log -1 origin/main -- <file>: if it prints a commit, the file is protected.
  • A prompt hook: a hook type that sends the payload to a model with a question. It can judge vaguer rules ("is this migration safe to edit?"), at the price of a model call and of a non-deterministic answer. For a question with an exact answer in a table, the query is better.
  • Code review: catches it, but after Claude has built more work on top.

Destructive Artisan commands

migrate:fresh and db:wipe are routine on a local SQLite database, and a disaster if .env happens to point at a shared or production database. A deny rule on Bash(php artisan migrate:fresh*) would block both cases, which makes it useless for local development. The hook can look at the database configuration that the command would actually use:

php
 1<?php
 2
 3namespace App\Console\Commands\Agent;
 4
 5class GuardArtisan extends HookCommand
 6{
 7    protected $signature = 'agent:guard-artisan';
 8
 9    protected $description = 'PreToolUse hook: deny destructive Artisan commands outside a local database';
10
11    private const DESTRUCTIVE = '/artisan\s+(migrate:(fresh|refresh|reset|rollback)|db:wipe)\b/';
12
13    protected function handleHook(): int
14    {
15        $command = (string) $this->payload('tool_input.command');
16
17        if (! preg_match(self::DESTRUCTIVE, $command, $matches)) {
18            return self::SUCCESS;
19        }
20
21        if ($this->databaseIsLocal()) {
22            return self::SUCCESS;
23        }
24
25        $connection = config('database.default');
26
27        return $this->deny(
28            "{$matches[1]} would run against the '{$connection}' connection, which is not a local database. Ask the user to run it themselves."
29        );
30    }
31
32    private function databaseIsLocal(): bool
33    {
34        $config = config('database.connections.'.config('database.default'));
35
36        if ($config['driver'] === 'sqlite') {
37            return true;
38        }
39
40        // 'mysql' and 'pgsql' are the Sail service names.
41        return app()->isLocal()
42            && in_array($config['host'] ?? null, ['127.0.0.1', 'localhost', 'mysql', 'pgsql'], true);
43    }
44}
json
 1{
 2  "matcher": "Bash",
 3  "hooks": [
 4    {
 5      "type": "command",
 6      "if": "Bash(php artisan *)",
 7      "command": "php \"$CLAUDE_PROJECT_DIR/artisan\" agent:guard-artisan"
 8    }
 9  ]
10}

The if field uses the same syntax as permission rules, so the command only boots Laravel for Artisan commands, and every other Bash call skips the 150 ms. It also understands compound commands: cd /path/to/app && php artisan db:wipe --force was caught too.

To try it, I started Claude with DB_CONNECTION=mysql DB_HOST=db.prod.internal in the environment and asked it to run migrate:fresh --seed. The hook inherits Claude's environment, so it saw the same configuration the command would have used, and denied it. Claude relayed the reason and told me to run the command myself if I really wanted to. On the default SQLite configuration, the same command went through.

Where else this rule could live.

  • A deny rule: right if you never want Claude to run these commands, on any database.
  • "permissionDecision": "ask": the same hook can ask you to confirm the command, which is a softer version for when the database might be remote but you want the option.
  • The database itself: the real protection for production is that your development machine has no credentials with DROP privileges on it. The hook is a seatbelt for when that is not true.

Running the tests before Claude stops

The Stop event fires when Claude is about to hand control back. A hook that exits with 2 there sends Claude back to work, with stderr as the reason. This one runs Pest when PHP files have changed:

bash
 1#!/usr/bin/env bash
 2input=$(cat)
 3cd "$CLAUDE_PROJECT_DIR" || exit 0
 4
 5# Nothing changed in PHP files: nothing to test.
 6git status --porcelain -- '*.php' | grep -q . || exit 0
 7
 8output=$(vendor/bin/pest --compact 2>&1) && exit 0
 9
10# Claude already had one go at fixing it: let it stop and warn the human.
11if [[ $(jq -r '.stop_hook_active' <<< "$input") == true ]]; then
12  jq -n '{systemMessage: "The test suite is still failing."}'
13  exit 0
14fi
15
16echo "The test suite is failing. Fix it before you finish:" >&2
17echo "$output" | tail -n 40 >&2
18exit 2
json
 1{
 2  "hooks": {
 3    "Stop": [
 4      {
 5        "hooks": [
 6          { "type": "command", "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pest.sh\"", "timeout": 300 }
 7        ]
 8      }
 9    ]
10  }
11}

The stop_hook_active check was not in my first version. I tested it with a conflicting request: I asked for a Money::format() that returns € 12.34, with a space, while an existing test expected €12.34. Claude wrote what I asked, the hook blocked it, and Claude correctly refused to choose between my instruction and the test on its own. It asked me which one to change. The hook blocked again, and again: nine round trips before the run ended. A failure that needs a human decision cannot be fixed by sending Claude back. With the check, Claude gets one retry, and after that it stops and the user sees the warning.

In the case the hook is designed for, it works on the first round. With a test expecting EUR 12.34 and a prompt that left the format open, Claude's first version failed, the hook sent it back with the Pest output, Claude matched the test, and the suite went green.

A variant runs the tests in the background after each edit. With "asyncRewake": true on a PostToolUse hook, the script does not block Claude, and if it exits with 2, its stderr wakes Claude up as a new message, even in the middle of other work:

json
 1{
 2  "matcher": "Edit|Write",
 3  "hooks": [
 4    {
 5      "type": "command",
 6      "command": "\"$CLAUDE_PROJECT_DIR/.claude/hooks/pest-background.sh\"",
 7      "asyncRewake": true,
 8      "timeout": 300
 9    }
10  ]
11}

I verified it with Claude busy on a sleep 25 after the edit: the failure report arrived during the sleep and Claude fixed the code. It gives feedback earlier than Stop, at the cost of running the suite on every edit. With a suite that takes seconds, it is a good trade. With a suite that takes minutes, Stop is better.

Where else this rule could live.

  • CLAUDE.md ("run the tests before you finish"): Claude usually does it, but it also decides when the tests are relevant, and sometimes decides they are not.
  • A pre-commit hook: running the full suite on every commit is slow enough that people start skipping it with --no-verify.
  • CI: mandatory anyway. The hook just moves most failures from the pull request to the session, where fixing them is cheaper.

Context at session start

A SessionStart hook can add text to Claude's context before the first prompt. This one tells Claude what it is working on:

php
 1<?php
 2
 3namespace App\Console\Commands\Agent;
 4
 5class SessionContext extends HookCommand
 6{
 7    protected $signature = 'agent:context';
 8
 9    protected $description = 'SessionStart hook: tell Claude about this app';
10
11    protected function handleHook(): int
12    {
13        $migrator = app('migrator');
14        $files = array_keys($migrator->getMigrationFiles([database_path('migrations')]));
15        $ran = $migrator->repositoryExists() ? $migrator->getRepository()->getRan() : [];
16        $pending = array_values(array_diff($files, $ran));
17
18        $lines = [
19            'Laravel '.app()->version().' on PHP '.PHP_VERSION.', environment: '.app()->environment().'.',
20            "Default database connection: '".config('database.default')."'.",
21            $pending === []
22                ? 'All migrations have run.'
23                : 'Pending migrations: '.implode(', ', $pending).'.',
24        ];
25
26        return $this->addContext(implode("\n", $lines));
27    }
28}
json
 1{
 2  "hooks": {
 3    "SessionStart": [
 4      {
 5        "hooks": [
 6          { "type": "command", "command": "php \"$CLAUDE_PROJECT_DIR/artisan\" agent:context" }
 7        ]
 8      }
 9    ]
10  }
11}

Without a matcher, the hook fires on every source: new sessions, --resume, /clear, and after compaction, which is where context tends to get lost. Asked without tools what it knew about the app, Claude answered "Laravel 13.37.0, PHP 8.5.9, sqlite, all migrations have run", and added that this was a snapshot from the start of the session.

That last remark points to the limit of this approach: the context is a snapshot. Anything that changes during the session (a new migration, a switch of branch) is stale ten minutes later.

Where else this rule could live.

  • CLAUDE.md: right for what does not change, such as conventions, architecture, and commands. A fresh Laravel 13 app already ships a CLAUDE.md, whose first instruction is to install Laravel Boost.
  • Laravel Boost: generates guidelines for the installed packages and exposes MCP tools (schema, routes, logs, Tinker) that Claude calls when it needs them. Live data on demand beats a snapshot. If you use Boost, keep the hook for the few things you want Claude to know before it asks, such as pending migrations.
  • Code that explains itself: some context belongs in the codebase. I wrote about that in Less telepathic codebases.

More ideas

The same pieces cover other rules. A few that I did not develop here:

  • Static analysis: a PostToolUse hook that runs Larastan on the edited file and returns errors to Claude with "decision": "block". Analysing a single file misses errors in callers, so the full run stays in CI.
  • Prompt guardrails: UserPromptSubmit can add context to every prompt, or block prompts that contain something that looks like a secret.
  • Notifications: the Notification event fires when Claude waits for a permission or for input. A notify-send or a Slack webhook saves you from checking the terminal.
  • Audit log: an async PostToolUse hook on Bash that appends each command to storage/logs/agent.log, without slowing anything down.

Sharing hooks with a team

Hooks in .claude/settings.json and the scripts in .claude/hooks/ go in the repository, so everybody who opens the project with Claude Code gets the same guarantees. The Artisan commands live in app/, so they are versioned, reviewed and tested like the rest of the code.

A few practical points:

  • the Bash scripts need jq and must be executable; commit them with the executable bit set;
  • personal hooks (notifications, for example) belong in .claude/settings.local.json, so they do not end up in everybody's setup;
  • /hooks inside Claude Code lists every active hook and the file it comes from, which is the first thing to check when a hook does not fire;
  • a hook runs with your user's permissions, so review changes to .claude/ with the same attention as changes to a CI workflow. It is code that runs on every developer's machine.

Other coding agents have hooks too: Cursor, GitHub Copilot, Codex CLI and Gemini CLI offer similar mechanisms, with comparable events and their own names and payloads. The examples here are Claude's, but the reasoning about where a rule should live carries over.

Where each rule lives

Rule CLAUDE.md Permission rule Claude hook Git hook CI
Format with Pint as a reminder – PostToolUse redundant pint --test
Protect .env, lock files – deny overkill – –
Migrations that already ran as a reminder too coarse PreToolUse + Artisan – –
Destructive Artisan commands as a reminder if never allowed PreToolUse + if – –
Tests pass as a reminder – Stop or asyncRewake too slow mandatory
App context stable facts – SessionStart snapshot – –

The pattern is consistent. A fixed list of paths or commands goes in a permission rule. A rule that needs to look at the application, the database or the tests goes in a hook, and in a Laravel app that hook can be an Artisan command. Preferences and conventions stay in CLAUDE.md, and CI remains the last check, because it is the only one that runs on every change whoever made it.

Get the next posts by email

An occasional newsletter with my new Posts, with one-click unsubscribe. How I handle your address.