Sulat.com / Writing on AIMonday, November 30, 2026
Enter →
Developer Tools/30 November 2026

Clean Code in Laravel version 4 adds AI agent rules

Ahmad Mayahi's free Laravel book has a Security chapter, a chapter on tracking AI costs and an installer that writes its rules for nine coding tools. Here's what's in it and what happened when I ran it.

Glossy 3D red slab held by a robot arm above a stack of three dark slabs, the Clean Code in Laravel book's mark
Illustration: Sulat, featuring the Clean Code in Laravel cover mark

At a glance

  • Version 4 of Ahmad Mayahi's free Laravel book adds a Security chapter, a chapter on tracking AI costs with his Spectra package, and two bonus chapters on clean code in the AI era. It is updated for Laravel 13.44.
  • One installer writes the book's 17 rule files, and an optional skill, in the formats of nine coding tools. On a fresh Laravel 13.44.1 project it ran cleanly, re-ran without changes and uninstalled what it added.
  • In my five-model test, the models passed 30 of 35 checks with the rules installed and 14 of 35 without them. It was one task and one run per model, so it is a smoke test.
  • The book is free to read under CC BY-NC-ND 4.0, which bars commercial use and derivatives. Its author also created Spectra, the package chapter 27 covers, and says so in the chapter.

Ahmad Mayahi has released version 4 of Clean Code in Laravel, his free book of Laravel conventions, updated for Laravel 13.44. It adds a Security chapter, a chapter on tracking AI costs with his Spectra package, two bonus chapters on clean code in the AI era, and a one-line installer that writes the book’s rules for nine coding tools. I read the book, then ran the installer, the Claude Code plugin and a five-model test on a fresh Laravel project.

Disclosure: I’m an OpenAI, Firecrawl and Devin ambassador.

29

chapters in four parts and a bonus, free to read online

17

rule files for AI agents, one per topic

9

coding tools the installer writes for

What the book is

Clean Code in Laravel is a practical guide to Laravel conventions, written by Ahmad Mayahi, a developer with almost 20 years in PHP. He published it in October 2025 and this is version 4.0. It is free to read on his site, the source is a public GitHub repository of Markdown chapters, and there’s a PDF download. It runs to close to 100,000 words, code samples included.

Its pitch is that Laravel makes it easy to build things, and that the trouble shows up three months later when nobody can follow the code. The book’s answer is conventions: thin controllers, Actions for business logic, Data Transfer Objects, Form Requests, View Models, lean Eloquent models, custom query builders, enums and the State pattern, with testing, queues, security and deployment at the end.

It isn’t dogmatic about it. The preface says the patterns solve problems at a certain scale, and that a solo developer building a five-route CRUD app doesn’t need Actions, DTOs and Form Requests for every endpoint. It names the opposite of spaghetti code “ravioli code”, dozens of tiny classes that each do almost nothing, and says a GetFlightsAction that only calls Flight::active()->get() has gone too far. The case for the patterns is team consistency: on a team, “use your judgment” means five developers make five different calls.

What changed in version 4

The book’s own “What’s New” page lists the changes. The headline items:

  • A Security chapter. Audit Composer and npm packages in CI on every pull request and on a schedule, turn findings into a single GitHub issue that updates and closes itself, block deployments on a failed audit, and secure the pipeline, secrets and production configuration.
  • A chapter on AI observability with Spectra. Track every AI request, its cost and its latency, enforce budgets per user or team, and alert on errors and spend.
  • Two bonus chapters on why clean code still matters when AI writes much of it, and on teaching an agent your conventions.
  • AI rules and a Claude Code skill, covered below.
  • Laravel 13 updates across chapters: #[RetryFor] and #[DebounceFor] for jobs, #[FailOnUnknownFields] on Form Requests, model attributes such as #[Table], #[Hidden] and #[ObservedBy], #[Scope] for scopes, a Pest architecture-testing section, and a first look at Laravel’s AI SDK.
  • Tooling updates: PHPStan 2, a table that now covers level 10, current GitHub Actions versions, PHP 8.5 in the deployment commands and Deployer 8.

The book targets PHP 8.5. A note in it says PHP 8.6 shipped on 19 November, that Laravel 13 officially supports PHP 8.3 to 8.5, and that the AI rules tell agents to use PHP 8.6 features only when a project requires them. It lists the versions it covers: Laravel 13.44, Pest 4 and 5, PHPStan 2.3 with Larastan 3.15, Rector 2.9, Pint 1.32, Horizon 5.52 and Laravel Boost 2.10.

The chapters

Hand-drawn list of the book's four parts and bonus: Think, Write, Model and Ship Clean, plus two AI-era chapters
Four parts and a bonus, 29 chapters in all. Illustration: Sulat. Source: the book’s table of contents.

Think Clean has four chapters: the philosophy of simplicity, naming conventions, code quality and automation, and dependency injection. The core rules read as a checklist before any code: is this the simplest way, will a new team member understand it in thirty seconds, and does it follow Laravel’s own conventions. It also rules out the Repository pattern on top of Eloquent, because Eloquent is already the data-access layer.

Write Clean is the longest part, with twelve chapters: controllers, Actions, DTOs, organising an application, Form Requests, View Models, jobs, pipelines, APIs, webhooks, rate limiting and authorization. The controller rules are the book’s best-known stance. A controller receives, delegates and returns, with at most the seven resource methods, and a custom action such as publish becomes CRUD on a new resource: PublishedPostController@store rather than PostController@publish.

Model Clean has five chapters: Eloquent models, custom query builders and collections, enums with value objects and type safety, the State pattern, and database practice. Ship Clean has six: testing, queue workers, packages, security, deployments and the AI observability chapter. The two bonus chapters close the book, followed by a short thank-you.

The AI observability chapter makes the case that an AI call is now the slowest, most expensive and least predictable dependency in many Laravel apps, and that logs and generic monitoring can’t answer what a feature costs or who spends the most. It names Laravel Pulse and Laravel Nightwatch as good tools for the wrong level of detail, since they see an HTTP request and not a model, a token count or a price. It then walks through installing Spectra, protecting its dashboard behind two gates, attaching context to calls, budgets and alerts. I haven’t installed Spectra, so that chapter is the one part of the book I read without running.

The AI rules and the installer

The ai-rules folder in the repository holds every convention from the book rewritten as direct instructions, in seventeen topic files: core principles, naming, controllers and routes, Actions and services, Form Requests and DTOs, views and APIs, jobs, webhooks and rate limiting, authorization, Eloquent, query builders, enums and states, database, testing, code quality, packages and deployment, and modern Laravel and PHP. The last one includes a table of the outdated patterns models tend to write next to what to write instead. The book’s reason for the rewrite is that “Never pass $request->all() to create()” is a rule an agent can follow, while an essay about mass assignment is something it has to interpret.

Code
curl -fsSL https://mayahi.net/laravel/ai-rules.sh | bash

Run in a terminal, the installer asks which tools you use, with Claude Code and Cursor ticked by default. It then asks, separately, whether to add the rules to AGENTS.md (No by default) and whether to install the skill (Yes by default). Flags skip the questions: --agent, --skills, --yes, --dir, --dry-run, --list and --uninstall.

Hand-drawn terminal window with an arrow to nine file icons: Claude Code, Cursor, Copilot, Windsurf, Devin, Junie, Codex, Gemini, Boost
One command, nine formats. Illustration: Sulat. Source: the book’s installer.

The nine targets are Claude Code, Cursor, GitHub Copilot, Windsurf, Devin Desktop, JetBrains Junie, AGENTS.md (read by Codex, Zed, Amp and others), Gemini CLI and Laravel Boost. The installer handles them in two different ways, which is the part of the design I found most considered.

Hand-drawn comparison: AGENTS.md, GEMINI.md and Junie read about 150 lines every time; other tools load 17 topic files on demand
Short rules for always-read files, 17 topic files for the rest. Illustration: Sulat. Source: the book, chapter 29.

Tools with path-scoped rules, which are Claude Code, Cursor, Copilot, Windsurf and Devin, get all seventeen files, because they load each one only when it applies. Files read on every request, which are AGENTS.md, GEMINI.md and Junie’s file, get only the core principles and the modern Laravel rules, about 150 lines, plus a table telling the agent which file in ai-rules/ to read before it touches controllers, jobs, models or tests. The agent pays for the detail only when it needs it. For AGENTS.md and GEMINI.md the installer writes between marker comments and leaves the rest of the file alone.

The second chapter of the bonus also covers enforcing conventions without the agent’s cooperation: a format-on-edit hook, and Pest architecture tests that fail when a rule is broken. One of its examples stops controllers using the DB facade. The book calls tests like that “the cheapest code review you will ever get”.

What I ran: the installer

I read the whole installer script before running it. It is a 1,212-line bash script that downloads the repository as a tarball from GitHub, unpacks it into a temporary directory, writes the files for the tools you pick, and removes the temporary directory at the end. Its deletions are limited to paths it created. Because the rules are fetched from the main branch at run time, the CCIL_REF variable pins a branch or tag, which is worth doing on a team.

The one-liner itself failed in my sandbox, because the tarball download from GitHub was blocked. The script has a documented escape hatch, CCIL_SOURCE, which points at a local checkout of the book, so I cloned the repository and used that. Everything below is that run. The project was a fresh composer create-project laravel/laravel, which gave Laravel 13.44.1 on PHP 8.3.6.

Code
CCIL_SOURCE=~/clean-code-in-laravel bash ai-rules.sh --agent all --skills all --yes
Terminal screenshot of the Clean Code in Laravel installer writing rules and skills for nine integrations into a Laravel project
The installer’s own output on a fresh Laravel 13.44.1 project.
Animated terminal replay of the installer output scrolling through each integration it writes
The installer’s output, replayed line by line.

It wrote 17 rules plus the skill for Claude Code, Cursor and Copilot, 17 rules each for Windsurf and Devin, and core rules plus a pointer folder for Junie, AGENTS.md and Gemini. The Laravel 13 starter ships an AGENTS.md that already holds a Laravel Boost block. The installer appended 166 lines after it, between its own markers, and left the Boost block untouched. The Boost target wrote .ai/guidelines/clean-code-laravel.md, which is the folder Boost’s documentation gives for project guidelines. I didn’t install Boost, so I didn’t run boost:update.

Running it a second time changed nothing: the file listing and checksum were identical and the diff was the same 166 lines. --uninstall removed every integration. It left one blank line at the end of AGENTS.md, which is the only trace.

What I ran: the Claude Code plugin

The book also ships a Claude Code plugin. The documented install is /plugin install clean-code-in-laravel --marketplace ahmadmayahi/clean-code-in-laravel. My Claude Code version took the older two-step form the README gives for older versions: add the marketplace, then install clean-code-in-laravel@clean-code-in-laravel. It installed as version 1.0.0.

To give it something to find, I wrote a deliberately bad OrderController: validation by hand, a query per item in a loop, a float discount, a raw email inside the request, and a cancel() method with no authorization.

Code
public function store(Request $request)
{
    $data = $request->all();
    if (!isset($data['email']) || !filter_var($data['email'], FILTER_VALIDATE_EMAIL)) {
        return response()->json(['error' => 'bad email'], 422);
    }
    $total = 0;
    foreach ($data['items'] as $i) {
        $p = DB::table('products')->where('id', $i['id'])->first();
        $total += $p->price * $i['qty'];
    }
    if ($total > 100) { $total = $total * 0.9; }
    $id = DB::table('orders')->insertGetId(['email' => $data['email'], 'total' => $total, 'status' => 'new']);
    Mail::raw('Thanks for order '.$id, fn($m) => $m->to($data['email']));
    return response()->json(['id' => $id, 'total' => $total]);
}

I ran the skill’s review command in a project with the rules installed, and a plain review prompt in a copy without them. Both prompts are below, word for word.

Code
/clean-code-in-laravel review app/Http/Controllers

Review app/Http/Controllers

Both reviews found the same real bugs: anyone can cancel any order, missing input crashes with a 500, a negative quantity lowers the price, the order is saved without its items, and the email goes out inside the request with no transaction. The skill’s review sorted them into must-fix, should-fix and consider, and its fixes mapped onto the book: a Form Request, an Action, a backed OrderStatus enum, an API Resource, route model binding with a policy, a queued mail after commit, and tests. It also read composer.json, saw ^8.3 and avoided PHP 8.5-only features, and chose PHPUnit because the project has no Pest. The plain review made the same functional points and added two the skill’s didn’t: store should return 201, and the routes need CSRF handling or an API route file. It didn’t suggest an Action, a DTO or an enum.

Then I asked the plugin to build the endpoint. The prompt, verbatim:

Code
/clean-code-in-laravel:clean-code-in-laravel build a POST /api/orders endpoint for the OrderController store logic: refactor app/Http/Controllers/OrderController.php so it follows the book, create what's needed, do not run migrations or composer

It created 16 files: a thin store() taking a StoreOrderRequest and a PlaceOrderAction, two DTOs, an OrderStatus enum, an API Resource, a queued OrderConfirmationMail, Order and Product models with factories and migrations, a route, and a feature test file. I ran the suite myself afterwards: 13 tests, 13 passed, 50 assertions. It left cancel() alone, as the skill tells it not to change unrelated code, and it flagged its own assumptions: it moved money to integer cents and assumed the old prices were dollars, so the discount threshold went from 100 to 10,000. It also said it couldn’t read the skill’s reference files in that headless run, because of a permission denial, and worked from the main instructions.

What I ran: five models, with and without the rules

The claim worth testing is that installing the rules changes what an agent writes. I used opencode as the harness and gave five models the same refactor task on the same messy controller, once in a project with the rules installed and once in a copy without them. The models were Kimi K3.1 Pro, DeepSeek V4.1 Flash, Claude Haiku 5.5, GPT-6.2 Sol and Gemini 4 Neon. This is the prompt, verbatim:

Code
Refactor the store method of app/Http/Controllers/OrderController.php so it follows Laravel best practice. Add the route, create any models, migrations and factories you need, and add feature tests for it. Leave cancel() alone. Do not run composer. When you are done, run php artisan test and tell me the result.

The prompt never mentions the book. In the rules-installed project each model found and opened the rule files or the skill on its own before writing code. I scored every result against seven checks taken from the book’s conventions: a Form Request, an Action class, a status enum, a DTO, an API Resource, a queued email, and a controller with no DB or Mail calls in store().

Terminal log of an opencode run where Kimi loads the clean-code-in-laravel skill then reads rule files for controllers, requests and models
Kimi K3.1 Pro loads the skill, then opens the rule files it needs.
ModelChecks without the rulesChecks with the rulesTests passing, without / with
Kimi K3.1 Pro1 of 77 of 75 / 7
DeepSeek V4.1 Flash3 of 74 of 79 / 9
Claude Haiku 5.53 of 76 of 712 / 19
GPT-6.2 Sol1 of 76 of 77 / 12
Gemini 4 Neon6 of 77 of 716 / 16
One run per model and condition. The tests are the ones each model wrote, and all of them passed in every run.
Hand-drawn contrast of two clipboards: without the rules 14 of 35 checks, with the rules 30 of 35
The same refactor task, five models. Illustration: Sulat. Source: our run.

Across the five models that is 14 of 35 checks without the rules and 30 of 35 with them, and every model scored higher or the same with the rules installed. The gains weren’t even. Kimi went from a Form Request and nothing else to all seven checks, and the OpenAI model went from one check to six. Gemini already did most of it unprompted and finished at seven. DeepSeek moved least: with the rules it added DTOs but still skipped the enum, the Resource and the queued mail. Claude Haiku added the enum, DTOs and Resource but sent the email synchronously.

Hand-drawn bar chart of checks passed out of 7 for Kimi, GPT, Claude, DeepSeek and Gemini, with and without the rules
Every model scored higher with the rules installed. Illustration: Sulat. Source: our run, one task, one run per model.

Two things to weigh before reading much into it. This is a smoke test: one task, one run per cell, so a one-point gap is noise. And I wrote the seven checks from the book’s own conventions, so the score measures how closely a model followed the book, not whether its code is better in general. A plain run that skipped the enum still produced passing tests and working code. The rules also cost time: every rules-installed run took about 1.3 to 1.5 times as long as its plain twin, because the agent reads the rule files first.

How it compares

Rules for coding agents are now a genre. Laravel’s own answer is Laravel Boost, a dev dependency that adds an MCP server, composable guidelines, agent skills and a documentation API with more than 17,000 pieces of Laravel knowledge. Spatie has packaged its house conventions as guidelines-skills. The book’s rules sit in a different layer from both.

OptionWhat it gives an agentInstall
Clean Code in Laravel rules17 topic files and a skill on where code lives: Actions, DTOs, Form Requests, enums, testscurl ... | bash, or the Claude Code plugin
Laravel BoostAn MCP server, version-aware framework guidelines, skills and a docs searchcomposer require laravel/boost --dev then php artisan boost:install
Spatie guidelines-skillsFour skills: Laravel and PHP conventions, JavaScript, version control and securitycomposer require spatie/guidelines-skills --dev, or npx skills add spatie/guidelines-skills
Per each project’s own documentation. I installed only the first.

Boost tells an agent what Laravel can do and which version it’s on. Spatie’s skills cover code style and naming. The book’s rules are the opinionated architecture layer on top: where business logic goes, when a DTO earns its place. They aren’t rivals, and the installer’s Boost target exists so the book’s core rules ride along with Boost’s. The long-running human-readable list in the same space is the laravel-best-practices repository, which I didn’t test as agent input. In the same spirit as the book’s tooling chapter, Pun, a Rust toolchain for PHP, goes after the format, lint and analyse steps that run underneath these rules.

Licence and the author

The book is free to read and share, but its licence is Creative Commons Attribution-NonCommercial-NoDerivatives 4.0. That bars commercial use and derivative works without the author’s permission, so it is free as in free to read, not open source in the usual sense. The Claude Code plugin’s manifest carries the same licence. Mayahi takes contributions through pull requests on the Markdown chapters.

He is the creator and maintainer of Spectra, the package chapter 27 covers, and of Chatvia.ai, an AI chatbot platform. The chapter says so itself: “I am its creator and maintainer, so weigh my opinions accordingly.” He has a second book on his site, Thinking in Domains in Laravel, which I haven’t read.

How to try it yourself

Use a throwaway Laravel project or a clean Git branch. Read the script first, then run bash ai-rules.sh --dry-run to see what would change, and pin CCIL_REF to a tag if you want the rules not to move under you. Commit the generated files so the whole team, and every agent session, shares them. In Claude Code, try /clean-code-in-laravel review app/Http/Controllers.


Sources: Clean Code in Laravel (mayahi.net and the ahmadmayahi/clean-code-in-laravel repository, including its installer script, ai-rules folder, skill and plugin manifest) / Laravel Boost documentation / Spatie guidelines-skills README.