Claude Code for PHP Developers: Laravel, WordPress & Composer Workflows (2026)

By Ask Patrick · June 2026 · 14 min read

PHP powers 77% of the web. Laravel is the most popular PHP framework. And almost nobody has written a real guide to using Claude Code with either of them. This is that guide — 30+ copy-paste prompts covering Laravel, Composer, PHPUnit, WordPress, Eloquent, and legacy PHP modernization.

What You'll Learn

  1. Why PHP + Claude Code is underrated
  2. CLAUDE.md setup for PHP projects
  3. Laravel: Artisan, Eloquent & routing prompts
  4. Composer & dependency management
  5. PHPUnit & Pest testing workflows
  6. WordPress & WooCommerce patterns
  7. Modernizing legacy PHP code
  8. Security & validation prompts
  9. Rolling out to a PHP team

Why PHP + Claude Code Is an Underrated Combination

The AI coding tool conversation is dominated by Python and TypeScript developers. But here's the reality: there are more PHP developers actively shipping production code than almost any other language. Laravel alone has millions of users. WordPress runs 43% of the internet.

PHP developers are underserved by AI tooling guides, which means two things:

Laravel's convention-over-configuration approach is a perfect match for Claude Code. Eloquent relationships, migrations, form requests, policies, observers — all follow predictable patterns. Once Claude understands your project structure, it can scaffold these instantly.

💡 Real-world result: A Laravel team using Claude Code for controller + test scaffolding reported cutting feature delivery time by 40% in their first month — not by writing less code, but by spending less time on boilerplate and more time on business logic.

Step 1: CLAUDE.md Setup for PHP Projects

The CLAUDE.md file is Claude Code's instruction manual for your project. Without it, Claude guesses your conventions. With it, Claude knows exactly how your team works.

Here's a production-ready CLAUDE.md template for Laravel projects:

# CLAUDE.md — Laravel Project

## Stack
- PHP 8.3
- Laravel 11.x
- MySQL 8 (dev) / PostgreSQL 15 (production)
- Redis for cache and queues
- Pest for testing
- Vite + Vue 3 for frontend

## Code Standards
- PSR-12 style, enforced via Laravel Pint
- Type-hinted everything — no untyped function params
- Strict mode: `declare(strict_types=1)` in all files
- Readonly properties where appropriate (PHP 8.2+)
- Use Laravel's built-in helpers; avoid raw PHP where equivalents exist

## Architecture
- Thin controllers → fat services (avoid fat models)
- Form Requests for all validation
- Policies for all authorization
- Events + Listeners for side effects (never in controllers)
- Repository pattern: NOT used — we use Eloquent directly
- Jobs for all async work

## Naming Conventions
- Controllers: singular, `UserController`, `OrderController`
- Models: singular, `User`, `Order`, `Product`
- Migrations: `create_orders_table`, `add_status_to_orders_table`
- Jobs: imperative verb, `ProcessPayment`, `SendWelcomeEmail`
- Events: past tense, `OrderPlaced`, `UserRegistered`

## Testing
- Pest for all tests
- Feature tests for all API endpoints
- Unit tests for service classes
- Use factories, never raw DB inserts
- Never test private methods directly — test behavior

## Environment
- `php artisan` for Artisan commands
- `./vendor/bin/pint` to fix code style
- `./vendor/bin/pest` to run tests
- `sail up` to start Docker environment

For WordPress or non-Laravel PHP projects, adapt the stack section accordingly. The key principle: tell Claude your naming conventions, testing tools, and architectural patterns explicitly.

Laravel: Artisan, Eloquent & Routing Prompts

Scaffolding Controllers and Resources

Prompt — Resource Controller

Create a full resource controller for managing Products in my Laravel 11 e-commerce app. Products have: name, slug, description, price (decimal), stock_quantity (int), category_id (FK), is_active (bool), and images (polymorphic). Include: Form Request for validation, Policy for authorization, Resource class for API responses, and Pest feature tests for all 7 routes. Follow PSR-12 and declare strict_types.

Prompt — API Controller with Pagination

Write an API controller for /api/v1/orders with index (paginated, filterable by status and date range), show, store, and update methods. Use Laravel's API Resource with conditional attributes. Include cursor pagination for index. Add rate limiting via RouteServiceProvider. Write Pest feature tests with RefreshDatabase.

Eloquent Relationships & Queries

Prompt — Eloquent Relationship Setup

I have these models: User, Order, OrderItem, Product, Category. Set up all Eloquent relationships (hasMany, belongsTo, hasManyThrough, morphTo as needed). Then write a query to get a user's last 5 orders with their items and product names, eager-loaded to avoid N+1. Add a query scope `scopeRecent` and `scopeByStatus` to the Order model.

Prompt — Complex Query Optimization

This Eloquent query is slow: [paste query]. Analyze it for N+1 issues, missing indexes, and over-fetching. Rewrite it using eager loading, select() to limit columns, and withCount() where appropriate. Show me the query log before and after using DB::enableQueryLog().

Migrations & Database

Prompt — Migration with Indexes

Create a migration for an `audit_logs` table. Columns: id (uuid), user_id (nullable FK to users), action (string 100), model_type, model_id (morphs), ip_address, user_agent, payload (json), created_at. Add indexes for: user_id, model_type+model_id (composite), action, created_at. Include a corresponding AuditLog model with casts and a factory.

Artisan Commands

Prompt — Custom Artisan Command

Create an Artisan command `app:sync-inventory` that: accepts a `--source` option (csv or api), reads a product inventory file or calls an external API, updates stock_quantity in the products table in batches of 100, logs each batch to Laravel's Log::channel('inventory'), sends a Slack notification on completion via a Job. Include a progress bar. Register it in the console kernel to run daily at 2 AM.

Composer & Dependency Management

Prompt — Dependency Audit

Review my composer.json and identify: packages that have newer major versions with breaking changes I should plan for, any packages with known security advisories, packages that duplicate functionality, and dev dependencies that accidentally ended up in require (not require-dev). Suggest a migration plan for the most critical updates.

Prompt — Package Evaluation

I need to add PDF generation to a Laravel app. Compare these options: barryvdh/laravel-dompdf, barryvdh/laravel-snappy, spatie/laravel-pdf (using Browsershot/Puppeteer), and league/html-to-markdown + a native PDF lib. My requirements: complex layouts with CSS, Arabic RTL text support, server-side generation without a browser. Recommend the best option and show the installation + basic usage.

Autoloader & PSR-4 Setup

Prompt — Domain Architecture Setup

I want to restructure my Laravel app into domain-based modules: Orders, Catalog, Customers, Payments. Each domain should have its own Models, Services, Repositories, Events, Jobs, and Http directories. Set up composer.json PSR-4 autoloading for this structure, create the directory tree, and show me how to register the service providers for each domain module.

PHPUnit & Pest Testing Workflows

Testing is where Claude Code earns its keep in PHP projects. Pest's expressive syntax and Laravel's testing helpers combine into something Claude can scaffold nearly perfectly.

Prompt — Feature Test Suite

Write a complete Pest feature test suite for the checkout flow: add item to cart, apply coupon, calculate shipping, process payment (mock Stripe), create order record, send confirmation email (assert queued). Use RefreshDatabase, create realistic factories, test happy path and error cases (out of stock, invalid coupon, declined card). Use describe() blocks to group related tests.

Prompt — Service Class Unit Tests

Write Pest unit tests for this OrderService class: [paste class]. Mock all dependencies (OrderRepository, PaymentGateway, EmailService). Test each public method with happy path, edge cases, and exception handling. Use Pest's `beforeEach` for shared setup. Aim for 100% branch coverage on the core business logic methods.

Prompt — Factory Setup

I have these models: User, Company, Project, Task, Comment. Create Eloquent factories for all of them with realistic fake data. Include states: User::factory()->admin(), User::factory()->suspended(); Project::factory()->overdue(), Project::factory()->completed(). Use model relationships in factories (tasks should auto-create a project if none is provided).

💡 Testing tip: Ask Claude to write the test before the implementation for new features. Laravel + Pest makes TDD surprisingly fast, and Claude can hold both the spec and the implementation in context simultaneously.

WordPress & WooCommerce Patterns

WordPress development has different conventions than Laravel, but Claude Code handles both well. The key is being explicit about your environment.

Prompt — WordPress Plugin Scaffold

Create a WordPress plugin scaffold for a custom post type called "Properties" (real estate listings). Include: plugin header, CPT registration with supports (title, editor, thumbnail, custom-fields), custom taxonomy "property-type", meta box for property details (price, bedrooms, bathrooms, sq_ft, address), custom REST API endpoint at /wp-json/properties/v1/listings with pagination, and a basic Gutenberg block to display a property card. Use OOP with a main plugin class.

Prompt — WooCommerce Hook Integration

I need to add custom functionality to WooCommerce: 1) Add a "Delivery Date" picker field on the product page that saves to order meta, 2) Show that date in the order admin view, 3) Include it in the order confirmation email, 4) Add it to the REST API order response. Use proper WooCommerce hooks (woocommerce_before_add_to_cart_button, woocommerce_checkout_fields, etc.) and avoid direct DB queries — use WC order meta functions.

Prompt — WordPress Performance Audit

Review this WordPress theme's functions.php: [paste file]. Identify: queries running on every page load that should be cached, missing transients, hooks firing on admin pages unnecessarily, scripts/styles loading everywhere instead of conditionally, and any direct $wpdb queries that could use WP_Query. Rewrite the worst offenders.

Modernizing Legacy PHP Code

One of Claude Code's highest-value use cases for PHP teams is dealing with legacy codebases — PHP 5.x code, procedural spaghetti, or MySQL queries mixed directly into HTML.

Prompt — PHP 5 to PHP 8 Migration

Modernize this PHP 5.6 class to PHP 8.3: [paste class]. Apply: constructor property promotion, readonly properties, enums instead of class constants, union types and nullables, named arguments where it improves clarity, match expressions over switch, fibers if appropriate, declare(strict_types=1). Preserve all existing behavior — do not change business logic. Show a diff-style view of changes.

Prompt — Procedural to OOP Refactor

This file is 800 lines of procedural PHP with global variables, mysql_* functions, and HTML mixed in: [paste file]. Refactor it to: separate the data layer (PDO), business logic (service class), and presentation (template). Identify what can be extracted into reusable functions or classes. Create a migration plan — I cannot rewrite it all at once, so show me the safest sequence of small refactors.

Prompt — SQL Injection Audit

Scan this PHP file for SQL injection vulnerabilities: [paste file]. For each unsafe query, show the vulnerable line and a safe rewrite using PDO prepared statements or Laravel's query builder. Also check for: XSS vulnerabilities (unescaped output), CSRF issues, insecure file uploads, and md5/sha1 password hashing that should be replaced with password_hash().

⚠️ When modernizing legacy code: Always ask Claude to explain its changes, not just make them. Legacy PHP often has undocumented business logic buried in side effects. Understanding why old code existed is as important as making it clean.

Security & Validation Prompts

PHP has a long history of security vulnerabilities. Claude Code can function as a security reviewer for your codebase.

Prompt — Form Request Validation

Create Laravel Form Requests for this API endpoint that accepts order creation: [describe fields]. Include: required/optional field rules, custom validation rules for business logic (e.g., stock availability check, delivery date must be future), proper error messages in the messages() method, validation for nested arrays (order items), and a prepareForValidation() method to normalize input (strip spaces, lowercase email, etc.).

Prompt — Security Review

Review my Laravel app's authentication and authorization layer: [paste routes/web.php, Policies, and middleware]. Check for: routes missing auth middleware, policies with overly permissive `before()` methods, mass assignment vulnerabilities in models (missing $fillable or $guarded), sensitive data in API resources, and missing rate limiting on auth endpoints. Give me a prioritized fix list.

Prompt — CORS & API Security

Set up proper CORS and API security for my Laravel API consumed by a React SPA on a different domain. Configure: CORS headers for the production and staging domains only, Sanctum SPA authentication, CSRF cookie setup, rate limiting per user (60 req/min) and per IP for unauthenticated routes (20 req/min), and API key auth for the mobile app as an alternative auth method. Show the config and middleware setup.

Rolling Out Claude Code to a PHP Team

Individual productivity gains are good. Team-wide adoption is where the real ROI shows up.

Week 1: Foundation

Week 2: Shared Prompt Library

Week 3-4: Process Integration

TaskWithout Claude CodeWith Claude Code
Resource controller + tests2-3 hours20 minutes
Migration + model + factory45 minutes10 minutes
Security audit of a controller30 minutes5 minutes
PHP 5 to 8 class modernization4 hours45 minutes
WooCommerce hook research1-2 hours15 minutes

The pattern is consistent: Claude Code doesn't replace your PHP expertise. It removes the time you spend on code you already know how to write — the boilerplate, the tests, the validation, the research. That time goes back into architecture decisions, code review, and building things that actually matter.

Get the Full Claude Code Team Playbook

The PHP prompts above are a starting point. The Team Playbook includes 200+ prompts across PHP, Python, TypeScript, Java, and Go — plus CLAUDE.md templates for 12 project types, a 4-week team rollout plan, and productivity benchmarking worksheets.

Get the Team Playbook — $49 →

Quick Reference: PHP Prompt Patterns That Work

A few meta-patterns that consistently produce great results with Claude Code for PHP:

1. Lead with the framework version. "Laravel 11" and "Laravel 9" have different conventions (route model binding, middleware syntax, etc.). Always specify.

2. Mention what NOT to use. "We don't use repositories, we use Eloquent directly" prevents Claude from generating patterns you'll have to rewrite.

3. Ask for tests in the same prompt. "Build X and write Pest tests for it" produces better-designed code than building first and testing second.

4. Paste the relevant code. For Eloquent issues, paste your model. For validation issues, paste the request. Claude Code's strength is context — give it context.

5. Ask for the migration plan on legacy work. "I cannot rewrite this all at once — give me the safest sequence of small refactors" is more practical than "rewrite this entire file."


PHP's reputation for being messy is largely a legacy of pre-framework, pre-Composer, pre-type-hint PHP. Modern PHP — especially Laravel — is clean, expressive, and a genuinely good language to build with. Claude Code makes it faster. That's a good combination.

Try the prompts above. Start with the one that matches your biggest current bottleneck — test writing, legacy modernization, or controller scaffolding. See what comes out. Adjust the prompt. Build the habit.