CLAUDE.md for Laravel/PHP Projects

Laravel has strong conventions. Thin controllers. Fat models or service classes. Eloquent relationships. Form Requests for validation. Route model binding. If you don’t encode those conventions in your CLAUDE.md, Claude might produce technically correct PHP that fights every pattern your team has established.

The good news: Laravel’s conventions are well-defined, which makes writing an effective CLAUDE.md straightforward. You’re mostly just telling Claude to follow the conventions Laravel already has — plus whatever project-specific choices your team has made on top of them.

📋 TL;DR
– Specify your Laravel version — patterns differ between Laravel 10 and 11
– Define your frontend stack clearly: Blade, Livewire, or Inertia.js + frontend framework
– Thin controllers are a Laravel best practice — make this explicit in your CLAUDE.md
– Specify your migration and testing patterns to avoid inconsistent output
– A complete copy-ready template is included at the bottom

This is part of our complete CLAUDE.md — The Complete Beginner’s Guide (2026). If you’re new to CLAUDE.md, start with What to Put in Your CLAUDE.md (With Real Examples).


Why Laravel Projects Need Explicit CLAUDE.md Rules

Laravel has an official way to do most things. But many of those official ways have evolved across versions, and there are also legitimate debates within the community (service classes vs fat models, repositories vs direct Eloquent, etc.).

Without explicit guidance, Claude might:

  • Write validation logic inside controllers instead of Form Request classes
  • Return raw Eloquent models from APIs instead of Resource classes
  • Use DB:: facade with raw queries instead of Eloquent ORM
  • Write migration logic directly in controllers instead of using php artisan make:migration
  • Create monolithic controller methods instead of single-action controllers
  • Forget declare(strict_types=1) if you require it
  • Mix old-style PHP 7 patterns with modern PHP 8.x syntax

Your CLAUDE.md eliminates all of this by stating your choices clearly.


Section 1: Laravel Version and PHP Version


## Version Information
- PHP version: 8.3
- Laravel version: 11.x
- PHP features in use: readonly properties, enums, intersection types, match expressions
- Composer: 2.x

⚠️ Warning: Laravel 11 has a significantly simplified folder structure compared to Laravel 10 — the app/Http/Kernel.php is gone, middleware is registered differently, and there’s no app/Console/Kernel.php. If you’re on Laravel 11, Claude needs to know so it uses the correct registration patterns.


Section 2: Frontend Stack

Laravel is flexible about its frontend. Blade-only, Livewire, or Inertia.js are all common and completely different in their patterns.

Blade templates only:


## Frontend Stack
- Frontend: Blade templates only
- Styling: Tailwind CSS v3 via Laravel Mix / Vite
- No JavaScript framework — Alpine.js for lightweight interactivity
- No Livewire — server-side rendering via Blade

### Blade Conventions
- Template names: kebab-case (`user-profile.blade.php`)
- Layouts defined in `resources/views/layouts/`
- Components in `resources/views/components/`
- Never put business logic in Blade templates — views should only display data

Livewire:


## Frontend Stack
- Frontend: Livewire 3 (full-stack components)
- Styling: Tailwind CSS
- Livewire components in `app/Livewire/`
- Views in `resources/views/livewire/`

### Livewire Conventions
- One Livewire component per feature/section of the UI
- Use wire:model.live for real-time updates, wire:model for form submissions
- Validate in Livewire component methods using $this->validate()
- No raw JavaScript manipulation of Livewire state — use $dispatch or $emit

Inertia.js with Vue:


## Frontend Stack
- Frontend: Inertia.js + Vue 3 (Composition API)
- Styling: Tailwind CSS
- Vue components in `resources/js/Pages/` (page components) and `resources/js/Components/`
- No separate API — Inertia handles data passing via props

### Inertia Conventions
- Laravel controllers return `Inertia::render('Page/Name', $data)` — not JSON
- Use `usePage()` in Vue for shared props (auth user, flash messages)
- Form submission via Inertia's `useForm()` helper — not raw axios
- File structure mirrors the Laravel route structure

Inertia.js with React:


## Frontend Stack
- Frontend: Inertia.js + React 18 (TypeScript)
- Styling: Tailwind CSS
- React components in `resources/js/Pages/` and `resources/js/Components/`

### Inertia + React Conventions
- TypeScript for all React components and utility files
- Named exports for all components — no default exports
- Use `usePage<PageProps>()` for accessing shared Inertia props
- Form handling: `useForm()` from `@inertiajs/react`

Section 3: Controller Conventions

This is a key decision point in Laravel projects. Specify your approach clearly.


## Controller Conventions

### Thin Controllers
Controllers should be thin — they receive HTTP requests, delegate to services,
and return responses. Business logic does not belong in controllers.

### Single Action Controllers
Prefer single-action controllers for non-CRUD endpoints:
- `php artisan make:controller ProcessPaymentController --invokable`
- One controller file = one action = one responsibility

### Resource Controllers
Use resource controllers for standard CRUD:
- `php artisan make:controller UserController --resource`
- Use `Route::resource()` in routes
- Only include the methods your resource actually needs (`only` or `except`)

### Controller Return Types
- Web routes: return views or redirects (Blade) / Inertia responses (Inertia)
- API routes: return Resource classes — never return raw Eloquent models
- Redirects: use named routes (`to_route('users.index')`)

### Validation
- Always use Form Request classes — never `$request->validate()` in controllers
- Generate with: `php artisan make:request StoreUserRequest`
- Form Requests live in `app/Http/Requests/`

Section 4: Models and Eloquent


## Models and Eloquent

### Model Conventions
- Models in `app/Models/`
- All models have explicit `$fillable` — never use `$guarded = []` in production
- All relationships must be defined with proper return type declarations
- Use model accessors/mutators (casts) instead of manual conversion in services

### Eloquent Patterns
- Use `with()` to eager load relationships — eliminate N+1 queries
- For complex queries: custom query scopes or repository methods
- Avoid chaining complex Eloquent queries in controllers — extract to model scope or service
- Use `firstOrCreate()`, `updateOrCreate()` instead of manual find-or-create logic

### Type Declarations on Relationships

// Required: return type declarations on all relationships

public function posts(): HasMany

{

return $this->hasMany(Post::class);

}

public function author(): BelongsTo

{

return $this->belongsTo(User::class, ‘author_id’);

}



### Model Events vs Observers
- Use Model Observers for side effects triggered by model events
- Observers in `app/Observers/` — register in a Service Provider
- Don't use model `boot()` method for complex logic — use Observers instead

Section 5: Services and Business Logic


## Service Layer

### Where Business Logic Lives
All business logic belongs in Service classes — not controllers, not models.

### Service Conventions
- Location: `app/Services/`
- Naming: `[Domain]Service.php` (e.g. `InvoiceService.php`, `PaymentService.php`)
- Injected via constructor dependency injection — not the `app()` helper
- Services throw exceptions on failure — controllers catch and convert to HTTP responses
- One service per domain/bounded context — don't create a God service

### Example Pattern

// Controller — thin

class InvoiceController extends Controller

{

public function __construct(private readonly InvoiceService $invoices) {}

public function store(StoreInvoiceRequest $request): RedirectResponse

{

$invoice = $this->invoices->createFromRequest($request->validated());

return to_route(‘invoices.show’, $invoice);

}

}

// Service — business logic lives here

class InvoiceService

{

public function createFromRequest(array $data): Invoice

{

// Validation, calculations, side effects all here

}

}



Section 6: API Development


## API Development (if this project has an API)

### API Routes
- All API routes in `routes/api.php`
- API version prefix: `/api/v1/` (even if we only have v1 — plan for the future)
- All API routes use Sanctum authentication middleware

### JSON Responses
- Always use Laravel API Resources — never return raw Eloquent models
- Resource classes in `app/Http/Resources/`
- Resource Collections for lists: `UserResource::collection($users)`
- Consistent response structure across all endpoints

### API Resource Pattern

class UserResource extends JsonResource

{

public function toArray(Request $request): array

{

return [

‘id’ => $this->id,

‘name’ => $this->name,

’email’ => $this->email,

‘created_at’ => $this->created_at->toISOString(),

// Never expose: password, remember_token, internal IDs

];

}

}



### Error Handling
- Return consistent error responses via custom exception handler
- API validation errors: 422 with JSON errors
- Not found: 404 with JSON message
- Unauthorized: 401, Forbidden: 403

Section 7: Database and Migrations


## Database and Migrations

### Migration Rules
- Never edit existing migration files — only create new ones
- Migration naming: descriptive of the change
  (`php artisan make:migration add_avatar_url_to_users_table`)
- Every migration must have a working `down()` method
- Always use `foreignId()` and `constrained()` for foreign keys with cascade rules

### Eloquent and Queries
- No raw `DB::statement()` except for operations Eloquent can't handle
- Always paginate large result sets — never `->get()` on unbounded queries
- Index foreign keys and commonly-filtered columns in migrations

### Seeding
- Seeders in `database/seeders/`
- Factories in `database/factories/`
- Production seeds (e.g. roles, plan types) in a separate seeder from dev data

Section 8: Testing


## Testing

### Setup
- Testing framework: Pest 2 (preferred) [or PHPUnit directly]
- Run tests: `php artisan test` or `./vendor/bin/pest`
- Test database: separate test database in `.env.testing`

### Pest Conventions
- Feature tests in `tests/Feature/` — test full HTTP request/response cycle
- Unit tests in `tests/Unit/` — test individual classes and methods in isolation
- Use Pest's `it()` and `describe()` blocks for readable test names

### What to Test
- Every HTTP endpoint (status codes, response structure, auth requirements)
- Business logic in Service classes
- Form Request validation rules
- Policy and Gate authorization rules

### Testing Patterns
- `RefreshDatabase` trait for tests that need database state
- Factories for test data — never hard-code test records
- `actingAs()` for authenticated requests
- Mock external services (payment gateways, email, SMS) — never hit real APIs in tests

The Full Template


# [Project Name] — Claude Code Instructions

## Project Overview
[What this Laravel application does, who uses it, current stage and priorities.]

## Version Information
- PHP: [8.1 / 8.2 / 8.3]
- Laravel: [10 / 11]
- Composer: 2.x

## Frontend Stack
- [Blade only / Livewire / Inertia + Vue / Inertia + React]
- Styling: Tailwind CSS
- Build tool: Vite

## Coding Standards
- declare(strict_types=1) at the top of all PHP files
- PSR-12 coding standard
- Return type declarations on all methods
- Type hints on all function parameters
- Naming: PascalCase classes, camelCase methods/variables, snake_case DB columns

## Laravel Patterns
- Thin controllers — business logic in Service classes
- Form Requests for all input validation
- API Resource classes for all API responses — never return raw models
- Eager load relationships — no N+1 queries
- Single Action controllers for non-CRUD endpoints

## Folder Structure
- `app/Http/Controllers/` — thin controllers
- `app/Http/Requests/` — Form Request classes
- `app/Http/Resources/` — API Resource classes
- `app/Models/` — Eloquent models
- `app/Services/` — business logic
- `app/Observers/` — model observers
- `database/migrations/` — never edit existing migrations

## Commands
- Dev server: `php artisan serve`
- Run tests: `php artisan test`
- Migrate: `php artisan migrate`
- Make controller: `php artisan make:controller [Name]Controller --resource`
- Make model: `php artisan make:model [Name] --migration --factory --seeder`
- Queue worker: `php artisan queue:work`
- Cache clear: `php artisan optimize:clear`

## Testing
- Framework: Pest 2 [or PHPUnit]
- Feature tests for all HTTP endpoints
- Unit tests for Service classes
- Always use factories — never hard-code test data
- Mock external services

## Constraints
- Never edit existing migration files
- Always ask before adding Composer packages
- No business logic in controllers
- No raw SQL unless Eloquent can't handle it
- No exposed sensitive fields in API Resources
- All credentials via .env — never hardcoded

Common Mistakes in Laravel CLAUDE.md Files

Forgetting declare(strict_types=1). If your team uses strict types, add it to your CLAUDE.md. Claude won’t include it by default.

Not specifying the validation approach. Claude will sometimes put $request->validate() directly in controllers. If you always use Form Requests, say so explicitly.

Leaving out API Resource requirements. Returning raw Eloquent models from API endpoints exposes all model attributes by default — including timestamps, hidden fields, and more than you intend. Make Resource classes mandatory in your CLAUDE.md.

Not specifying your Pest vs PHPUnit preference. These have different syntax. Specify which one you use.


Key Takeaways

  • Laravel version matters** — especially between Laravel 10 and 11, which have different structural conventions
  • Frontend stack shapes everything** — Blade, Livewire, and Inertia.js projects have fundamentally different patterns
  • Thin controllers are the golden rule** — encode this explicitly so Claude doesn’t put logic where it doesn’t belong
  • Form Requests and API Resources** are Laravel’s official pattern for validation and API responses — make them mandatory
  • Never modify existing migrations** — encode this as a hard constraint to protect your database history

Next Steps

Return to CLAUDE.md — The Complete Beginner’s Guide (2026) for the full picture.