Kokil Thapa - Professional Web Developer in Nepal
Freelancer Web Developer in Nepal with 15+ Years of Experience

Kokil Thapa is an experienced full-stack web developer focused on building fast, secure, and scalable web applications. He helps businesses and individuals create SEO-friendly, user-focused digital platforms designed for long-term growth.

Prompt Patterns for Writing Better Code

By Kokil Thapa | Last reviewed: September 2026

Most developers treat AI like a search box and wonder why the output needs heavy rewriting. Prompt patterns for writing better code fix that by giving the model role, scope, constraints, and a verification step before you paste anything into your repo. On production Laravel and PHP work, the difference is not smarter models alone. It is structured prompts that mirror how you would brief a junior developer on a real ticket. This guide maps the patterns I use daily when integrating LLM APIs and AI assistants into application development workflows, with copy-paste templates you can adapt tonight.

What are prompt patterns for writing better code?

Prompt patterns are named templates you reuse across tickets. Each pattern answers four questions the model cannot guess: what file or module, what must not change, what “done” looks like, and how you will verify the result. Without those four anchors, you get confident code that compiles locally but breaks deployment assumptions.

Think of patterns as the coding equivalent of design patterns. You do not invent a new conversation structure for every bug. You pick “scoped refactor,” “test-first feature,” or “explain-then-patch,” then fill in project-specific details from your codebase.

Prompt Pattern AnatomyRoleSenior Laravel devContextFiles + stackConstraintsNo schema changeOutputDiff + testsVerification StepList assumptions, risks, and manual test stepsBad prompt: "Fix my checkout"Good pattern: scoped file list + acceptance criteria + forbidden edits
Prompt patterns for writing better code follow a repeatable five-part flow from role definition through verification.

The core patterns worth memorising are listed below. Each one maps to a common engineering task you already perform without AI.

  • Persona + scope: Define stack version and boundaries (“Laravel 13, PHP 8.3, change only Form Request and policy”).
  • Context sandwich: Paste relevant code above and below the change window so the model sees imports and return types.
  • Constraint block: Explicit negatives—no new packages, no migrations, no renaming public methods.
  • Example-driven: Show one existing method that matches your style; ask the model to mirror it.
  • Plan-then-code: Require a numbered plan before any diff; reject plans that touch unrelated layers.
  • Test-first: Ask for failing PHPUnit or Pest tests, then implementation to green them.
  • Diff-only output: Force unified diff or file blocks so you can apply patches mechanically.

For deeper theory on steering model behaviour, see the companion piece on prompt engineering techniques for better output and the practical prompt engineering playbook. Those articles cover temperature, few-shot examples, and chain-of-thought. This article focuses on patterns you paste into Cursor, Copilot Chat, or Claude when you need shippable code.

Which prompt patterns work best for Laravel and PHP projects?

Laravel codebases reward patterns that respect framework conventions. The model will happily invent a `CheckoutService` with static helpers if you do not tell it to use Form Requests, policies, and Eloquent relationships the way your app already does. Anchor every prompt to your actual layer boundaries.

The stack header block

Start every Laravel prompt with a fixed header. I reuse the same block across tickets on client projects running Laravel 12 or 13:

Stack: Laravel 13.x, PHP 8.3+, MySQL 9.7, Redis 8.10 for cache/queues.
Rules: Use Form Requests for validation. Use policies for authorization.
Do not add packages. Match existing PSR-12 style in pasted files.
Output: unified diff only. Max 3 files changed unless I approve expansion.

That header alone cuts hallucinated facades and deprecated helper usage. It also aligns with Laravel best practices for clean, efficient code you would enforce in human review anyway.

Feature pattern: test-first with acceptance criteria

When adding behaviour—say, validating a booking date on a travel portal—use this skeleton:

Role: Laravel developer on a booking module.

Task: Reject tour start dates in the past and dates during blocked seasons.

Acceptance criteria:
1. StoreBookingRequest returns 422 with field error on start_date.
2. BlockedSeason model dates are respected (relationship already exists).
3. Feature test covers valid date, past date, blocked season.

Constraints:
- Do not alter migrations or BlockedSeason schema.
- Do not change route URLs (SEO-sensitive).

Step 1: Write failing Pest/PHPUnit tests in tests/Feature/Booking/...
Step 2: Show minimal implementation diff.
Step 3: List manual QA steps.

I have used this pattern on production booking systems similar to trek and expedition management platforms. The test-first step forces the model to read your domain rules instead of guessing validation strings.

Refactor pattern: strangler with file lock

Legacy controllers fat with business logic are common. The strangler pattern prompt keeps scope narrow:

Refactor ONLY App\Http\Controllers\Admin\OrderController@store.
Extract pricing logic into App\Actions\Orders\CalculateOrderTotal.
Keep controller signature, route name, and response JSON shape identical.
Show before/after line counts. No new dependencies.

This mirrors incremental modernisation I prefer over big-bang rewrites. If you need governance beyond prompts, pair it with testing and optimisation reviews before merging.

Laravel Prompt Pattern PickerNew feature?Test-first patternAcceptance criteria + Form RequestProduction bug?Evidence-first debugLogs, repro steps, hypothesis listFat controller?Strangler refactor + file lockAPI integration?Contract-first + idempotent webhook
Choose Laravel prompt patterns by task type: features, bugs, refactors, and API integrations each need different constraints.

WordPress and WooCommerce work follows the same idea with a different header. Specify WordPress 7.1, hook names, and “no direct `$wpdb` unless existing file already uses it.” For greenfield modules, custom software development engagements benefit when prompts reference your coding standard document as an attachment.

How do you structure prompts for debugging production code?

Debugging prompts fail when they read like panic messages. Production incidents need evidence-first patterns: logs, expected vs actual behaviour, and a request to rank hypotheses before proposing patches.

Evidence-first debug template

Role: Production debugger for Laravel queue workers.

Symptom: Payment webhook jobs retry 5 times then fail silently for Khalti callbacks.

Evidence:
- Log excerpt: [paste 30 lines]
- Job class: App\Jobs\ProcessKhaltiWebhook (paste full file)
- Env: QUEUE_CONNECTION=redis, Redis 8.10, PHP 8.4-FPM

Task:
1. List 3 most likely root causes ranked by probability.
2. For top cause, propose smallest fix as unified diff.
3. State what log line proves fix worked.

Do not change payment amount logic or idempotency key format.

This pattern saved hours on payment integrations where gateway docs and application code diverge. It aligns with webhook reliability patterns you should already document in the repo.

Regression guard pattern

After the model proposes a fix, run a second prompt in the same thread:

Given your proposed fix, write one regression test that would have failed before the patch.
Use existing test factories. No new models.

That two-step loop turns AI output into something your CI can enforce. If you are building automated review, see adding AI code review to CI and building an AI review bot for GitLab for pipeline wiring—not prompt text alone.

When debugging regex or JSON payloads from APIs, validate assumptions with the on-site regex tester and JSON formatter before you paste malformed samples into the model. Garbage context produces garbage patches.

What prompt patterns reduce hallucinated APIs and bad diffs?

Hallucinations are usually context failures, not model mysteries. The model invents `User::active()` because you never pasted the User model. These patterns shrink the fiction surface.

PatternBest forKey constraint lineCommon failure without it
Context sandwichEditing mid-file logic“Here is full file; change only lines 40–65”Broken imports, wrong return types
API contract pasteREST integrations“Use only endpoints listed below”Invented URL paths and auth headers
Library version lockComposer/npm upgrades“Target Laravel 13.x; do not use removed helpers”Deprecated facade usage
Diff-onlyAny merge-bound work“No prose; unified diff hunks only”Unapplyable narrative answers
Assumption auditPre-merge review“List every assumption you made as bullets”Hidden schema changes
Human checklistSecurity-sensitive code“Confirm mass-assignment guards and policy checks”Missing authorization

Official references still matter. When integrating Shopify Admin APIs, paste a link to the current quarterly version—2026-07 or later per Shopify’s Admin API documentation—and instruct the model to cite only that version. For Laravel upgrades, point to the Laravel 13 upgrade guide instead of trusting training cutoffs.

On API-heavy builds, combine prompt patterns with REST API development practices your team already documents in OpenAPI. Paste the relevant schema fragment into the prompt so generated clients match reality.

Prompt to Merge PipelinePatternTemplate + contextAI diffUnified patchHuman gateScope checkTests + CIPHPUnit/PestReject if diff touches forbidden layersRe-prompt with tighter file lockMerge when tests green + review passesDocument pattern in team playbook
Human review gates between AI-generated diffs and merge prevent prompt patterns for writing better code from becoming unreviewed autopilot.

Multi-file change pattern

When a ticket spans controller, request, and test, sequence prompts instead of asking for everything at once:

  1. Paste models and policies; ask for plan only.
  2. Approve plan; request test file diff.
  3. Run tests locally; paste failures back for iteration.
  4. Request implementation diff capped at two files.
  5. Run assumption audit prompt before opening the PR.

Sequencing beats one giant prompt every time. It mirrors how advanced Form Request validation patterns are introduced incrementally in mature codebases.

How do you integrate prompt patterns into daily development workflow?

Patterns only help if they live where you work—not in a forgotten Notion page. Treat prompts as repo artefacts alongside code coverage gates and lint rules.

Build a team prompt playbook

Create `docs/ai-prompts/` in the repository with one markdown file per pattern: `feature-test-first.md`, `debug-evidence-first.md`, `refactor-strangler.md`. Each file contains the template and two filled examples from real tickets sanitised of client data. New developers copy the template instead of improvising.

On legal-tech portals and client dashboards I have maintained, document-sharing features demand strict authorisation language in every prompt:

Security constraints (non-negotiable):
- All document download routes must call DocumentPolicy@view.
- Never expose storage paths or S3 URLs in responses.
- Audit log entry required on download.

That block reflects patterns used on secure portals similar to client portals with document sharing. Generic “make it secure” prompts are worthless; named policies and routes are not.

Pair prompts with fine-tuning decisions

Most teams do not need custom models for internal CRUD. Prompt patterns plus good context windows handle Laravel feature work. When prompts stop scaling—high-volume classification, strict JSON from messy PDFs—read fine-tuning vs prompt engineering before committing budget. Fine-tuning is an ops project; patterns are a same-day habit.

Measure quality like any other tooling

Track simple metrics for two sprints: percent of AI diffs merged without rewrite, time-to-first-green-test, and post-merge revert count. If rewrite rate stays above fifty percent, your patterns are missing constraints—not model capacity.

Before vs After Prompt PatternsUnstructured promptVague ticket text500-line rewriteInvented helpersBroken importsLong review cyclesHigh revert riskPattern-based promptStack + constraintsSmall unified diffTests includedAssumption listFaster reviewShippable output
Structured prompt patterns for writing better code reduce rewrite volume and review time compared with one-line AI requests.

For WordPress/WooCommerce storefront work—multi-currency checkout, delivery zones—patterns should reference existing theme functions and WooCommerce 11.1 hooks explicitly. The same discipline applies to Laravel eCommerce builds with delivery-zone logic where business rules belong in prompts as numbered rules, not prose paragraphs.

If you are evaluating whether AI belongs in your delivery process at all, start with bounded tasks: docblocks, test scaffolds, migration stubs, and repetitive Blade partials. Expand only after patterns prove stable. That is the same incremental philosophy behind production web development on budget-conscious Nepal teams where rework is expensive.

External research on structured prompting for code continues to evolve. The OpenAI prompt engineering guide remains a useful cross-check for formatting and role instructions—even when your stack is PHP-first.

Key Takeaways

  • Reuse named prompt patterns (test-first, evidence-first debug, strangler refactor) instead of one-off chat messages.
  • Always lead with stack versions, forbidden edits, and output format—diff-only beats narrative answers.
  • Paste real files as context sandwiches; never ask the model to guess your Eloquent relationships or policies.
  • Sequence multi-file work: plan, tests, implementation, assumption audit—four prompts beat one megaprompt.
  • Store templates in `docs/ai-prompts/` and measure merge-without-rewrite rate like any CI quality gate.
  • Pair prompt patterns with human review and automated tests; AI accelerates typing, not accountability.

People Also Ask

Are prompt patterns the same as prompt engineering?

Prompt engineering is the broader skill of steering model behaviour—temperature, few-shot examples, chain-of-thought, tool use. Prompt patterns for writing better code are reusable templates within that skill, tuned for IDE workflows and merge-bound diffs. You need both, but patterns are what you paste daily.

Which AI coding tool works best with these patterns?

Any tool that accepts multi-file context and returns editable diffs works: Cursor, GitHub Copilot Chat, Claude Code, JetBrains AI Assistant. The pattern matters more than the vendor. Prefer tools that let you pin files and run terminal tests without leaving the editor.

Should juniors rely on prompt patterns for learning?

Patterns help juniors produce reviewable output faster, but they must read the generated code line by line. Require explanation prompts—“justify each change in one sentence”—so learning stays active. Patterns supplement fundamentals; they do not replace understanding Laravel’s request lifecycle or SQL indexes.

When do prompt patterns stop working?

They fail on large undocumented legacy code, missing tests, or tasks that require org-specific security knowledge you have not written down. Fix the documentation gap first, or restrict prompts to isolated modules until context exists.

Ship better AI-assisted code starting today

Prompt patterns for writing better code turn AI from a novelty into a repeatable part of your delivery pipeline. Pick one pattern—test-first feature or evidence-first debug—use it on your next ticket, and save the filled prompt in your team playbook. Combine that habit with solid review and CI, and you get speed without surrendering the standards you would apply to any human PR. If you want help integrating AI assistants into Laravel, WordPress, or API workflows without breaking production, contact us or explore AI integration and automation services. For more background, browse the blog or read about my approach on the about page.

Frequently Asked Questions

Repeatable templates—role, context, constraints, examples, and output format—that steer AI toward small, testable diffs instead of speculative rewrites.

No. Prompt engineering is the broader skill of steering model behaviour—temperature, few-shot examples, chain-of-thought, and tool use. Prompt patterns for writing better code are named, reusable templates within that skill, tuned for IDE workflows and merge-bound diffs. You need both, but patterns are what you paste daily into Cursor, Copilot Chat, or Claude when you need shippable code rather than exploratory chat.

Laravel codebases reward patterns that respect framework conventions: Form Requests for validation, policies for authorization, and Eloquent relationships instead of invented service classes. Anchor every prompt with a stack header listing Laravel 13.x, PHP 8.3+, MySQL 9.7, and Redis 8.10. Match task type to pattern—test-first for features, strangler for refactors, evidence-first for production bugs. Without layer boundaries, the model will happily invent static helpers and deprecated facades.

Start every Laravel prompt with a fixed header reused across tickets. Specify stack versions, framework rules, and output format. A practical block: Stack Laravel 13.x, PHP 8.3+, MySQL 9.7, Redis 8.10 for cache and queues. Rules: Form Requests for validation, policies for authorization, no new packages, match existing PSR-12 style. Output: unified diff only, max three files changed unless you approve expansion. That header alone cuts hallucinated facades and deprecated helper usage.

Define role, task, numbered acceptance criteria, and explicit constraints before any code. Example: reject past tour start dates and blocked-season dates via StoreBookingRequest returning 422, with a feature test covering valid, past, and blocked cases. Step one: write failing Pest or PHPUnit tests. Step two: show minimal implementation diff. Step three: list manual QA steps. The test-first step forces the model to read your domain rules instead of guessing validation strings.

Use it on legacy controllers fat with business logic when you want incremental modernisation, not a big-bang rewrite. Lock scope to one method: refactor ONLY OrderController@store, extract pricing into CalculateOrderTotal action, keep controller signature, route name, and response JSON shape identical. Require before and after line counts, no new dependencies. This mirrors how mature codebases introduce changes safely—one narrow extraction at a time with identical external behaviour.

Production incidents need evidence-first patterns, not panic messages. Paste logs, expected versus actual behaviour, and ask the model to rank hypotheses before proposing patches. Template: define role, symptom, evidence block with log excerpt and full job class file, environment details, then task steps—list three ranked root causes, propose smallest fix as unified diff, state what log line proves success. Add explicit constraints like do not change payment amount logic or idempotency key format on payment integrations.

After the model proposes a debug fix, run a second prompt in the same thread: given your proposed fix, write one regression test that would have failed before the patch, using existing test factories and no new models. That two-step loop turns AI output into something your CI can enforce. Pair it with automated review pipelines if you are building GitLab or CI-based AI review—not prompt text alone.

Hallucinations are usually context failures, not model mysteries. The model invents User::active() because you never pasted the User model. Patterns that shrink the fiction surface include context sandwich for mid-file edits, API contract paste for REST integrations, library version lock for upgrades, diff-only output for merge-bound work, assumption audit before merge, and human checklist for security-sensitive code. For Shopify Admin API work, paste the current quarterly version—2026-07 or later—and instruct the model to cite only that documentation.

When editing mid-file logic, paste the full file with a clear change window: here is the full file, change only lines 40 through 65. The model sees imports, return types, and surrounding code above and below the edit. Without it, you get broken imports and wrong return types because the model guesses relationships and namespaces. Combine with constraint blocks listing explicit negatives—no new packages, no migrations, no renaming public methods—so the edit stays mechanically applyable.

Sequence prompts instead of one megaprompt. Paste models and policies, ask for plan only. Approve the plan, request test file diff. Run tests locally, paste failures back for iteration. Request implementation diff capped at two files. Run an assumption audit prompt before opening the PR. Sequencing mirrors how mature codebases introduce Form Request validation incrementally—four focused prompts beat one giant request every time.

Treat prompts as repo artefacts, not forgotten Notion pages. Create docs/ai-prompts/ with one markdown file per pattern—feature-test-first, debug-evidence-first, refactor-strangler—each containing the template and two sanitised real-ticket examples. New developers copy templates instead of improvising. For security-sensitive portals, add non-negotiable constraint blocks naming specific policies and routes. Track metrics for two sprints: percent of AI diffs merged without rewrite, time-to-first-green-test, and post-merge revert count.

Any tool accepting multi-file context and editable diffs: Cursor, GitHub Copilot Chat, Claude Code, JetBrains AI Assistant. The pattern matters more than the vendor. Prefer tools that let you pin files and run terminal tests without leaving the editor. Prompt patterns are tool-agnostic templates—you paste the same role, constraint, and diff-only structure regardless of which assistant sits in your IDE.

Patterns help juniors produce reviewable output faster, but they must read generated code line by line. Require explanation prompts—justify each change in one sentence—so learning stays active. Patterns accelerate typing and structure; they do not replace understanding Form Requests, policies, or why a diff touches three files. Human review gates between AI-generated diffs and merge remain mandatory. AI accelerates delivery, not accountability.

Most teams do not need custom models for internal CRUD—prompt patterns plus good context windows handle Laravel feature work. When prompts stop scaling—high-volume classification, strict JSON from messy PDFs—evaluate fine-tuning versus prompt engineering before committing budget. Fine-tuning is an ops project; patterns are a same-day habit. Start with bounded tasks like docblocks, test scaffolds, migration stubs, and repetitive Blade partials. Expand only after patterns prove stable and rewrite rate drops below fifty percent.

Share this article

0 Comments

Leave a comment

Your email is not published. Comments appear once they have been read. Sign in to have your details filled in.

Quick Contact Options
Choose how you want to connect me: