Skill: relunctance/laravel-docs-reader (version 1.0.0)

# Laravel Docs Reader — Skill Specification ## Overview **Skill Name**: Laravel Docs Reader **Type**: Development Reference Skill **Target**: OpenClaw Agent and Laravel developers **Version**: 1.0.0 --- ## Core Objectives 1. Provide instant, accurate access to official Laravel documentation during coding 2. Auto-detect the local Laravel version and serve the correct docs 3. Generate standard Laravel code that conforms to Laravel best practices and PSR-12 4. Highlight version differences across Laravel 10 / 11 / 12 5. Keep references up to date via GitHub Actions auto-PR --- ## Version Support | Version | Status | Notes | |---------|--------|-------| | Laravel 12 | ✅ Default | Latest stable | | Laravel 11 | ✅ Supported | Full reference | | Laravel 10 | ✅ Supported | Full reference | --- ## Version Detection (Auto-Switch) When the agent runs on a project, it auto-detects Laravel version: 1. `composer.json` → `"laravel/framework": "^12.x"` 2. `artisan --version` 3. `vendor/laravel/framework/src/Illuminate/Foundation/Application.php` → `VERSION` constant Detection path: `references/version-detection.md` --- ## CLI Tool ```bash php laradoc.php <command> [args] ``` | Command | Args | Description | |---------|------|-------------| | `search` | `<query>` | Natural language search (with Package Search cross-link) | | `version` | `[path]` | Detect local Laravel version | | `current` | — | Show default version | | `config` | `<file>` | Config reference (database/cache/mail/...) | | `facade` | `<name>` | Facade method signatures | | `artisan` | `<cmd>` | Artisan command help | | `diff` | `<feature>` | Version diff (auth/routing/middleware/exception) | | `generate` | `<type> <name>` | Code skeleton (controller/model/job/middleware) | | `lang` | `<query>` | Blade directive lookup | | `psr` | `[topic]` | PSR-12 quick reference (full/arrays/naming/methods) | | `cache` | — | Show local cache status | | `update` | — | Force-refresh cache from GitHub | | `subscribe` | — | Show subscription / auto-update status | --- ## Search Coverage | Category | Topics | |----------|--------| | Routing | Basic routes, route groups, resource routes, named routes, middleware | | Controllers | CRUD, REST, API, single-action, dependency injection | | Models | Eloquent, relationships (12 types), mutators, scopes | | Migrations | Schema builder, foreign keys, indexes, modifiers | | Validation | Form requests, inline validation, custom rules | | Auth | Breeze, Sanctum, Gates, Policies, JWT | | Queues | Jobs, dispatching, failed job handling, Laravel Horizon | | Cache | Store API, tags, atomic locks | | Mail | Markdown, attachments, queuing | | Notifications | Multi-channel, database notifications | | Testing | Feature tests, unit tests, Pest, factories | | Events | Listeners, broadcasting, queueable events | | Storage | Local/S3/FTP, temporary URLs, uploads | | Scheduling | Cron, recurring jobs, prevention of overlap | | Service Container | Binding, singletons, contextual binding | | Facades | All 30+ facades with method signatures | | Broadcasting | Private/public channels, presence channels | | Configuration | database, cache, mail, queue, auth, session | --- ## Code Generation The `generate` command outputs standard Laravel code for: - `controller` — RESTful API controller - `model` — Eloquent model with fillable/casts/relationships - `job` — Queueable job with failed handler - `middleware` — HTTP middleware - `request` — Form Request validation - `notification` — Multi-channel notification - `factory` — Model factory for testing All output follows PSR-12 and Laravel conventions. --- ## Version Diff | Feature | Laravel 10 | Laravel 11 | Laravel 12 | |---------|-----------|-----------|-----------| | Auth scaffolding | `laravel new --auth` | Breeze | Breeze (minimal) | | Middleware registration | `Kernel.php` | `bootstrap/app.php` | `bootstrap/app.php` | | Route registration | `RouteServiceProvider` | `bootstrap/app.php` | `bootstrap/app.php` | | Exception handling | `app/Exceptions/Handler` | `bootstrap/app.php` | `bootstrap/app.php` | | Cycle tasks | `app/Console/Kernel.php` | `routes/console.php` | `routes/console.php` | | Broadcast channels | `routes/channels.php` | `routes/channels.php` | `routes/channels.php` | --- ## Auto-Update Mechanism A GitHub Actions workflow runs weekly to: 1. Fetch latest `laravel/framework` version from Packagist 2. Compare against the skill's default version 3. If new version detected → auto-create a PR with updated references ``` .github/workflows/update-docs.yml ├── Schedule: Every Sunday 00:00 UTC └── Creates PR: updates SKILL.md + version-detection.md ``` Anyone using this skill can review the auto-PR and merge after verification. --- ## File Structure ``` laravel-docs-reader/ ├── SKILL.md # This file ├── README.md # English (default) ├── README.zh-CN.md # Chinese ├── .github/ │ └── workflows/ │ └── update-docs.yml # Auto-update PR workflow ├── .cache/ # Local doc cache (auto-created) ├── references/ │ ├── version-detection.md # Version detection logic │ ├── version-diff.md # Version diff table (10/11/12) │ ├── psr-12.md # PSR-12 quick reference │ ├── api-index.md # Full API index │ ├── artisan-commands.md # All artisan commands │ ├── facades.md # Facade method signatures │ ├── blade-directives.md # All Blade directives │ ├── config-ref.md # Config file reference │ └── examples/ │ ├── controller.md │ ├── model.md │ ├── migration.md │ ├── middleware.md │ ├── queue-job.md │ ├── notification.md │ └── testing.md └── scripts/ └── laradoc.php # CLI tool (14 commands) ``` ## PSR-12 Quick Reference Built-in PSR-12 standard reference — no external formatter needed: ```bash php laradoc.php psr # Full PSR-12 table (rules + examples) php laradoc.php psr arrays # Arrays rule php laradoc.php psr naming # Naming conventions (class/method/var/const) php laradoc.php psr methods # Visibility + method rules php laradoc.php psr namespace # use statements php laradoc.php psr operators # Operator spacing ``` Topics: `arrays`, `naming`, `methods`, `control`, `namespace`, `operators` ## Local Cache (Offline Mode) The skill stores docs in `.cache/` for fast, offline access: ```bash php laradoc.php cache # Show cache status, size, age, offline availability php laradoc.php update # Force-refresh from GitHub ``` Cache is created automatically on first search. All bundled reference files work without internet. ## Auto-Update & Subscription GitHub Actions runs weekly (Sunday 00:00 UTC): - Detects new `laravel/framework` version from Packagist - Auto-creates PR updating `SKILL.md`, `version-detection.md`, `version-diff.md` - User reviews PR → merges when ready ```bash php laradoc.php subscribe # Show current subscription / update status ``` ## Laravel Package Search Cross-Link After every `search` result, the agent suggests `laravel-package-search` for third-party package discovery. --- ## Usage in OpenClaw When the agent needs to write Laravel code: 1. Auto-detect project Laravel version 2. Map the request to the correct doc section 3. Return: - Official documentation summary - Code example (PSR-12, Laravel best practice) - Version differences (if applicable) - Notes / caveats --- ## Evaluation Criteria Each doc entry is rated on: | Criterion | Description | |-----------|-------------| | Accuracy | Matches official Laravel docs exactly | | Completeness | Covers all common use cases | | Freshness | Updated for latest Laravel version | | Code Quality | PSR-12 compliant, idiomatic Laravel | | Version Coverage | Covers 10 / 11 / 12 differences | --- ## Publishing ```bash clawhub login --token <TOKEN> clawhub publish laravel-docs-reader ``` Or submit at https://clawhub.com

path: README.md
content: # Laravel Docs Reader

**English** | [中文](README.zh-CN.md)

---

## Overview

**Laravel Docs Reader** is an OpenClaw Agent Skill that gives agents (and developers) instant access to accurate, version-aware Laravel documentation. No more guessing — the agent looks up the official docs before writing a single line of code.

### Key Features

- 🔍 **Natural Language CLI Search** — `php laradoc.php search "how to create a queue job"` — works like asking the docs directly
- 📦 **Local Doc Cache** — docs bundled in the skill for offline, instant access; no internet required after first run
- 🔄 **Auto Version Detection** — detects your project's Laravel version (10/11/12) and serves the right docs
- 📖 **Full Documentation Coverage** — routing, controllers, models, queues, mail, auth, events, broadcasting, testing, and more
- 🏭 **Code Generation** — generates PSR-12 compliant Laravel code skeletons
- 📊 **Version Diff** — highlights what changed across Laravel 10 / 11 / 12
- 📋 **PSR-12 Quick Reference** — built-in, no external tool needed: `php laradoc.php psr`, `psr arrays`, `psr naming`
- 🤖 **Auto-Update via PR** — GitHub Actions workflow watches for new Laravel releases and auto-creates a PR to update this skill
- 🔗 **Laravel Package Search** — after every search result, the agent suggests `laravel-package-search` for third-party package discovery

---

## CLI Tool — 14 Commands

```bash
# ── Core Search ──────────────────────────────────────────────
# Natural language search — ask the docs anything
php laradoc.php search "how to create a middleware"
php laradoc.php search "how to send a notification"
php laradoc.php search "queue job with retry and failure handling"
php laradoc.php search "redis cache with tags"
# ← Shows Package Search cross-link after every result

# ── Version ──────────────────────────────────────────────────
php laradoc.php version                     # auto-detect current project
php laradoc.php version /path/to/project   # specific project
php laradoc.php current                     # show default (Laravel 12)

# ── Config & Facades ─────────────────────────────────────────
php laradoc.php config database
php laradoc.php config cache
php laradoc.php config mail
php laradoc.php facade Cache
php laradoc.php facade DB
php laradoc.php facade Route

# ── Artisan & Diff ───────────────────────────────────────────
php laradoc.php artisan make:controller
php laradoc.php artisan migrate
php laradoc.php diff auth           # Laravel 10 vs 11 vs 12
php laradoc.php diff routing

# ── Code Generation ──────────────────────────────────────────
php laradoc.php generate controller UserController
php laradoc.php generate model     Post
php laradoc.php generate job       ProcessUpload
php laradoc.php generate request  StorePostRequest
php laradoc.php generate notification InvoicePaid

# ── Blade Directives ─────────────────────────────────────────
php laradoc.php lang "loop"
php laradoc.php lang "csrf"

# ── PSR-12 Quick Reference ───────────────────────────────────
php laradoc.php psr                  # Full PSR-12 summary table
php laradoc.php psr arrays          # Arrays rule only
php laradoc.php psr naming          # Naming conventions
php laradoc.php psr methods         # Visibility & method rules

# ── Cache & Update ────────────────────────────────────────────
php laradoc.php cache                 # Show cache status (offline OK)
php laradoc.php update               # Force-refresh from GitHub
php laradoc.php subscribe            # Show subscription / auto-update status
```

---

## Version Detection

The CLI auto-detects your project's Laravel version:

1. `composer.json` → `laravel/framework`
2. `artisan --version`
3. `vendor/laravel/framework/.../Application.php` → `VERSION`

If no project found, defaults to **Laravel 12**.

---

## Auto-Update via GitHub Actions

This skill stays current automatically:

- **Weekly check**: A GitHub Actions workflow runs every Sunday at 00:00 UTC
- **New version detection**: Compares Packagist's `laravel/framework` latest version
- **Auto-PR**: If a new Laravel version is detected, the workflow creates a PR updating the skill's references

```yaml
# .github/workflows/update-docs.yml
on:
  schedule:
    - cron: '0 0 * * 0'  # Weekly on Sunday
  workflow_dispatch:         # Manual trigger
```

Anyone using this skill can review the auto-generated PR before merging — no surprises.

---

## Coverage

| Category | Topics |
|----------|--------|
| Routing | Basic routes, groups, resource, named, middleware |
| Controllers | CRUD, REST, API, single-action, DI |
| Models | Eloquent, all 12 relationship types, scopes, casts |
| Migrations | Schema builder, foreign keys, indexes |
| Validation | Form requests, inline, custom rules |
| Auth | Breeze, Sanctum, Gates, Policies |
| Queues | Jobs, dispatching, Horizon |
| Cache | Store API, Redis tags, locks |
| Mail | Markdown, attachments, queuing |
| Notifications | Multi-channel, database |
| Testing | Pest, factories, fakes, HTTP tests |
| Events | Listeners, broadcasting |
| Storage | Local/S3, signed URLs |
| Scheduling | Cron, overlapping prevention |
| Container | Binding, singletons |
| Facades | 30+ facade method signatures |
| Broadcasting | Private/public channels |

---

## Quick Start

### Agent (OpenClaw)

When activated, the skill:

1. Detects project Laravel version (or uses default 12)
2. Maps your request to the correct doc section
3. Returns: summary + code example + version notes + best practices

### Developer (CLI)

```bash
git clone https://github.com/relunctance/laravel-docs-reader.git
cd laravel-docs-reader
php scripts/laradoc.php search "how to create a middleware"
```

---

## Installation

This is an OpenClaw Agent Skill.

```bash
clawhub install laravel-docs-reader
# or
clawhub login --token <YOUR_TOKEN> && clawhub publish laravel-docs-reader
```

---

## File Structure

```
laravel-docs-reader/
├── SKILL.md                         # Skill specification
├── README.md                         # English (this file)
├── README.zh-CN.md                  # Chinese
├── .github/workflows/
│   └── update-docs.yml              # Auto-update PR (weekly)
├── .cache/                          # Local doc cache (auto-created)
├── references/
│   ├── version-detection.md          # Version detection logic
│   ├── version-diff.md              # Laravel 10/11/12 diff
│   ├── psr-12.md                    # PSR-12 quick reference
│   ├── api-index.md                # Full API reference
│   ├── artisan-commands.md          # All artisan commands
│   ├── facades.md                  # Facade method signatures
│   ├── blade-directives.md          # All Blade directives
│   ├── config-ref.md               # config/ reference
│   └── examples/
│       ├── controller.md
│       ├── model.md
│       ├── migration.md
│       ├── middleware.md
│       ├── queue-job.md
│       ├── notification.md
│       └── testing.md
└── scripts/
    └── laradoc.php                  # CLI tool (14 commands)
```

---

## Contributing

Found outdated content or missing docs?
- Open an issue: https://github.com/relunctance/laravel-docs-reader/issues
- Or submit a PR directly

---

## License

MIT License


path: README.zh-CN.md
content: # Laravel Docs Reader / Laravel 文档阅读助手

**English** | **中文**

---

## 简介

**Laravel Docs Reader** 是一个 OpenClaw Agent Skill，为 Agent（和开发者）提供即时、准确、支持版本识别的 Laravel 官方文档访问。写代码前先查文档，不用再靠猜测。

### 核心功能

- 🔍 **自然语言 CLI 检索** — `php laradoc.php search "how to create a queue job"` — 像在问官方文档一样
- 📦 **本地文档缓存** — 文档内置在 skill 中，离线可用，响应速度快
- 🔄 **自动检测 Laravel 版本** — 检测项目版本（10/11/12），自动切换到对应文档
- 📖 **完整文档覆盖** — 路由、控制器、模型、队列、邮件、认证、事件、广播、测试等全部覆盖
- 🏭 **代码生成** — 生成符合 PSR-12 和 Laravel 最佳实践的代码骨架
- 📊 **版本差异对比** — 标注 Laravel 10 / 11 / 12 各版本的差异
- 📋 **PSR-12 速查** — 内置：`php laradoc.php psr`、`psr arrays`、`psr naming`，无需外部工具
- 🤖 **自动更新 PR** — GitHub Actions 每周检测新版本，自动创建 PR 更新文档引用
- 🔗 **Laravel Package Search 联动** — 每次搜索后 Agent 建议使用 `laravel-package-search` 发现第三方包

---

## CLI 工具 — 14 个命令

```bash
# ── 核心搜索 ──────────────────────────────────────────────────
php laradoc.php search "how to create a middleware"   # 自然语言检索
php laradoc.php search "how to send a notification"
php laradoc.php search "queue job with retry"
# ← 搜索结果后会自动提示安装 laravel-package-search

# ── 版本 ──────────────────────────────────────────────────────
php laradoc.php version                   # 自动检测当前项目版本
php laradoc.php version /path/to/project  # 指定项目
php laradoc.php current                  # 显示默认版本 (Laravel 12)

# ── 配置 & Facade ─────────────────────────────────────────────
php laradoc.php config database
php laradoc.php config cache
php laradoc.php facade Cache
php laradoc.php facade DB

# ── Artisan & 版本差异 ────────────────────────────────────────
php laradoc.php artisan make:controller
php laradoc.php diff auth              # Laravel 10 vs 11 vs 12

# ── 代码生成 ──────────────────────────────────────────────────
php laradoc.php generate controller UserController
php laradoc.php generate model         Post
php laradoc.php generate job          ProcessUpload
php laradoc.php generate notification InvoicePaid

# ── Blade 指令 ────────────────────────────────────────────────
php laradoc.php lang "loop"
php laradoc.php lang "csrf"

# ── PSR-12 速查 ────────────────────────────────────────────────
php laradoc.php psr                   # 完整 PSR-12 规则表
php laradoc.php psr arrays           # 数组格式规则
php laradoc.php psr naming           # 命名规范
php laradoc.php psr methods         # 可见性与方法规范

# ── 缓存 & 更新 ───────────────────────────────────────────────
php laradoc.php cache                  # 查看本地缓存状态
php laradoc.php update                 # 强制从 GitHub 拉取最新文档
php laradoc.php subscribe              # 查看订阅 / 自动更新状态
```

---

## 版本自动检测

CLI 自动检测项目 Laravel 版本：

1. `composer.json` → `laravel/framework`
2. `artisan --version`
3. `vendor/laravel/framework/.../Application.php` → `VERSION`

未检测到项目时，默认为 **Laravel 12**。

---

## 自动更新机制（GitHub Actions PR）

Skill 保持最新的方式：

- **每周检查**：GitHub Actions 每周日 00:00 UTC 运行一次
- **新版本检测**：对比 Packagist 上的 `laravel/framework` 最新版本
- **自动 PR**：检测到新版本后，自动创建 PR 更新 skill 的文档引用

```yaml
# .github/workflows/update-docs.yml
on:
  schedule:
    - cron: '0 0 * * 0'  # 每周日
  workflow_dispatch:         # 也可手动触发
```

使用此 skill 的用户可以审核自动生成的 PR，确认无误后再合并。

---

## 文档覆盖范围

| 分类 | 覆盖主题 |
|------|---------|
| 路由 | 基础路由、路由组、资源路由、命名路由、中间件 |
| 控制器 | CRUD、REST、API、单动作、依赖注入 |
| 模型 | Eloquent、12 种关联、作用域、类型转换 |
| 迁移 | Schema 构建器、外键、索引、字段修饰符 |
| 验证 | Form Request、内联验证、自定义规则 |
| 认证 | Breeze、Sanctum、Gates、Policies |
| 队列 | Job、派发、失败处理、Laravel Horizon |
| 缓存 | Store API、Redis 标签、原子锁 |
| 邮件 | Markdown、附件、队列邮件 |
| 通知 | 多通道、数据库通知 |
| 测试 | Pest、工厂、Fakes、HTTP 测试 |
| 事件 | 监听器、广播、可队列化事件 |
| 存储 | Local/S3、签名 URL、上传 |
| 定时任务 | Cron、防重叠 |
| 服务容器 | 绑定、单例、上下文绑定 |
| Facades | 30+ Facade 方法签名 |
| 广播 | 私有/公开频道 |

---

## 快速开始

### Agent（OpenClaw）

激活后，skill 会：

1. 检测项目 Laravel 版本（未检测到则默认 12）
2. 将请求映射到对应文档章节
3. 返回：文档摘要 + 代码示例 + 版本注意事项 + 最佳实践

### 开发者（CLI）

```bash
git clone https://github.com/relunctance/laravel-docs-reader.git
cd laravel-docs-reader
php scripts/laradoc.php search "how to create a middleware"
```

---

## 安装方式

```bash
clawhub install laravel-docs-reader
# 或
clawhub login --token <YOUR_TOKEN> && clawhub publish laravel-docs-reader
```

---

## 文件结构

```
laravel-docs-reader/
├── SKILL.md                         # Skill 规范文档
├── README.md                         # 英文版（主）
├── README.zh-CN.md                  # 中文版
├── .github/workflows/
│   └── update-docs.yml              # 自动更新 PR（每周）
├── .cache/                          # 本地文档缓存（自动创建）
├── references/
│   ├── version-detection.md          # 版本检测逻辑
│   ├── version-diff.md              # Laravel 10/11/12 差异表
│   ├── psr-12.md                    # PSR-12 速查参考
│   ├── api-index.md                # 完整 API 索引
│   ├── artisan-commands.md         # Artisan 命令参考
│   ├── facades.md                 # Facade 方法签名
│   ├── blade-directives.md         # Blade 指令完整列表
│   ├── config-ref.md              # config/ 配置参考
│   └── examples/
│       ├── controller.md
│       ├── model.md
│       ├── migration.md
│       ├── middleware.md
│       ├── queue-job.md
│       ├── notification.md
│       └── testing.md
└── scripts/
    └── laradoc.php                # CLI 工具（14 个命令）
```

---

## 参与贡献

发现内容过时或缺少文档？
- 提交 Issue：https://github.com/relunctance/laravel-docs-reader/issues
- 或直接提交 PR

---

## 许可证

MIT License


path: references/psr-12.md
content: # PSR-12 Coding Standard Quick Reference

## Overview

PSR-12 is the extended coding style guide for PHP. All code generated by this skill complies with PSR-12.

---

## Key Rules at a Glance

### 1. Files

- PHP files MUST use `<?php` tag (no `<?=` unless outputting)
- Files MUST use UTF-8 without BOM
- Files SHOULD either declare symbols (classes, traits, etc.) or cause side effects (database operations, output), but NOT both
- Namespaces and classes MUST follow PSR-4 autoloading

```php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

class UserController extends Controller
{
    // ...
}
```

---

### 2. Lines & Indentation

- Use **4 spaces** for indentation (no tabs)
- Lines SHOULD be 120 characters or fewer; SOFT limit at 180
- One blank line after `namespace` declaration
- One blank line after block of `use` declarations
- `declare(strict_types=1)` MUST be first statement, with no blank lines before/after

```php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;

class UserController extends Controller
{
    public function show(int $id): JsonResponse
    {
        // 4 spaces, not tabs
    }
}
```

---

### 3. Namespaces & Use Statements

```php
<?php

declare(strict_types=1);

namespace App\Http\Controllers;        // ✓ ONE blank line after

use App\Models\User;                 // ✓ Blank line between groups
use Illuminate\Routing\Controller;  // ✓ Alphabetical within group
use Illuminate\Http\Request;
```

**Grouped imports** (PHP 7.0+ style):
```php
use Illuminate\Support\Facades\{Auth, Cache, DB};
```

---

### 4. Classes, Traits, Interfaces

- Opening `{` on same line with ONE space before
- Closing `}` on its own line
- `extends` on SAME line (no `implements` on separate line)

```php
// ✓ Correct
class UserController extends Controller implements HasFactory
{
}

// ✗ Wrong
class UserController
    extends Controller
    implements HasFactory
{
}
```

**Abstract classes**: `abstract class Example`
**Interfaces**: `interface Example`
**Traits**: `trait Example`

---

### 5. Methods & Functions

- Visibility (`public`, `protected`, `private`) MUST be declared on all properties and methods
- `abstract` and `final` come before `protected`/`public`
- `static` comes after visibility

```php
abstract protected static function factory(): static;
public    static function make(): static;
protected          $id;
private   static   $instance;
```

**Method chaining** (each method on new line):
```php
$query->where('active', true)
    ->orderBy('name')
    ->select('id', 'name')
    ->get();
```

---

### 6. Control Structures

```php
// if / elseif / else
if ($a === $b) {
    // ...
} elseif ($a === $c) {
    // ...
} else {
    // ...
}

// switch
switch ($variable) {
    case 'value1':
        // ...
        break;
    case 'value2':
        // ...
        break;
    default:
        // ...
}

// for / foreach / while
foreach ($items as $item) {
    // ...
}

// try / catch
try {
    // ...
} catch (FirstException $e) {
    // ...
} catch (OtherException $e) {
    // ...
}
```

---

### 7. match Expression (PHP 8.0+)

```php
$result = match ($status) {
    'active'   => 'User is active',
    'inactive' => 'User is inactive',
    'banned'   => 'User is banned',
    default   => 'Unknown status',
};
```

---

### 8. Operators

```php
// ✓ Spaces around operators
$a = $b + $c;
$name = isset($user) ? $user->name : 'Anonymous';

// ✗ No spaces inside parentheses
$name = isset($user) ? $user->name : 'Anonymous';

// Nullsafe operator (PHP 8.0+)
$country = $session?->user?->getAddress()?->country;

// Spaceship operator
$a <=> $b;  // Returns -1, 0, or 1
```

---

### 9. Strings

```php
// Concatenation: space before and after .
$greeting = 'Hello, ' . $name . '!';

// Heredoc / Nowdoc
$html = <<<HTML
<div class="card">
    <h1>{$title}</h1>
    <p>{$body}</p>
</div>
HTML;
```

---

### 10. Arrays

```php
// Short array syntax (PSR-12)
$items = ['first', 'second', 'third'];

// Trailing comma (allowed in PSR-12)
$items = [
    'first',
    'second',
    'third',  // ← trailing comma OK
];

// Associative
$config = [
    'host'     => '127.0.0.1',
    'port'     => 3306,
    'database' => 'forge',
];
```

---

### 11. Type Declarations (PHP 7.4+)

```php
class User
{
    public int    $id;
    public string $name;
    protected ?User $parent = null;

    public function __construct(
        public readonly string $email,
    ) {}

    public function getId(): int
    {
        return $this->id;
    }
}
```

**Return type**:
```php
public function getName(): string
{
    return $this->name;
}

public function getUser(): ?User  // nullable
{
    return $this->user;
}

public function setId(int $id): void  // void return
{
    $this->id = $id;
}
```

**Union types** (PHP 8.0+):
```php
public function getStatus(): string|int
{
    return $this->status;
}

public function getId(): int|null
{
    return $this->id;
}
```

---

### 12. Attributes (PHP 8.0+)

```php
#[Attribute]
class Documented
{
    public function __construct(
        public string $author,
        public ?string $version = null,
    ) {}
}

#[Documented(author: 'Laravel', version: '12')]
class Post extends Model
{
}
```

---

## Common PSR-12 Violations Checklist

| Check | Rule |
|-------|------|
| ☐ | `declare(strict_types=1)` is the first statement |
| ☐ | Indentation uses 4 spaces (not tabs) |
| ☐ | Opening brace ` `{ on same line as class/function declaration |
| ☐ | Visibility declared on ALL properties and methods |
| ☐ | `use` statements alphabetically ordered within groups |
| ☐ | One `use` statement per import (unless grouped) |
| ☐ | No trailing whitespace at end of lines |
| ☐ | Blank line before `return` (unless in nested structure) |
| ☐ | No hard tabs anywhere in the file |
| ☐ | Namespace has ONE blank line before first `use` |
| ☐ | Control structure keywords have ONE space before `( |
| ☐ | No space after function name before `(` |

---

## Laravel-Specific PSR-12 Notes

- **Controllers**: `App\Http\Controllers\`, one blank after namespace block
- **Models**: `App\Models\`, `$fillable`/`$casts`/`$hidden` as arrays with trailing commas
- **Jobs**: `App\Jobs\`, implement `ShouldQueue` with `use Dispatchable, Queueable, SerializesModels`
- **Migrations**: Method chain `$table->string()->unique()` where possible
- **Factories**: Return array, use `fake()->` for all generated data
- **Routes**: Closures in routes file should be avoided — use controllers

---

## Tooling

```bash
# Install PHP-CS-Fixer
composer require --dev friendsofphp/php-cs-fixer

# Check (dry-run)
./vendor/bin/php-cs-fixer fix --diff --dry-run --rules=@PSR12 app/

# Fix automatically
./vendor/bin/php-cs-fixer fix --rules=@PSR12 app/

# Laravel Pint (recommended)
composer require --dev laravel/pint
./vendor/bin/pint --test
./vendor/bin/pint  # auto-fix
```


path: references/version-detection.md
content: # Version Detection Logic

## Overview

When this skill runs against a Laravel project, it auto-detects the Laravel version using the following priority:

## Detection Priority

### 1. composer.json (Recommended)

```json
{
  "require": {
    "laravel/framework": "^12.0"
  }
}
```

Detection logic:
```php
$composer = file_get_contents('composer.json');
$data = json_decode($composer, true);
$laravelVersion = $data['require']['laravel/framework'] ?? null;
// Extract major version: "^12.0" → 12
preg_match('/\^?(\d+)/', $laravelVersion, $m);
$major = (int) $m[1]; // e.g. 12
```

### 2. artisan --version

```bash
$ php artisan --version
Laravel Framework 11.x.x
```

Detection logic:
```php
$output = shell_exec('php artisan --version');
preg_match('/Laravel Framework (\d+)/', $output, $m);
$major = (int) ($m[1] ?? 12);
```

### 3. Application.php VERSION constant

```php
// vendor/laravel/framework/src/Illuminate/Foundation/Application.php
const VERSION = '12.0.0';
```

Detection logic:
```php
$appFile = 'vendor/laravel/framework/src/Illuminate/Foundation/Application.php';
$content = file_get_contents($appFile);
preg_match('/const VERSION = \'(\d+)/', $content, $m);
$major = (int) ($m[1] ?? 12);
```

---

## CLI Usage

```bash
# Detect current project
php laradoc.php version

# Detect specific path
php laradoc.php version /path/to/project

# Show default
php laradoc.php current
```

---

## Version Mapping

| Composer Version | Artisan Output | Detected Major |
|-----------------|---------------|----------------|
| `^12.0` | Laravel Framework 12.x | 12 |
| `^11.0` | Laravel Framework 11.x | 11 |
| `^10.0` | Laravel Framework 10.x | 10 |

---

## Agent Behavior

When the agent processes a request:

1. Run `version_detect()` on the project root
2. If detected ≠ default (12), add a note to the response:
   > "Note: Your project uses Laravel {detected}, but this default is Laravel 12. Some features shown may differ."
3. All code examples use the detected version's syntax

---

## Fallback

If no Laravel project is found (e.g. running in an empty directory):
- Default to **Laravel 12**
- No version warning shown


path: references/version-diff.md
content: # Laravel Version Diff (10 / 11 / 12)

## Overview

This document highlights the key differences between Laravel 10, 11, and 12.

---

## Authentication

| Feature | Laravel 10 | Laravel 11 | Laravel 12 |
|---------|-----------|-----------|-----------|
| Auth Scaffolding | `laravel new --auth` (built-in) | Removed | Use Breeze |
| Recommended Auth | `laravel/breeze` | `laravel/breeze` | `laravel/breeze` (minimal) |
| API Auth | Sanctum (separate) | Sanctum | First-party |
| Session Guard | `config/auth.php` | `config/auth.php` | Still needed |
| Login Rate Limit | `Auth::attempt()` throttled | Kernel throttling | Rate limiter |

**Laravel 11+ Migration**: Run `composer require laravel/breeze && php artisan breeze:install`

---

## Routing

| Feature | Laravel 10 | Laravel 11 | Laravel 12 |
|---------|-----------|-----------|-----------|
| Route Files | `routes/web.php`, `routes/api.php` | `routes/web.php`, `routes/api.php` | Same |
| Route Registration | `RouteServiceProvider` (boot) | `bootstrap/app.php` | `bootstrap/app.php` |
| Route Config (views) | `Route::view()` in routes | `Route::view()` in routes | Same |
| Rate Limiting | `throttle` middleware in Kernel | `throttle:60,1` middleware | Rate limiter API |

**Laravel 11+**: Rate limiting now configured in `bootstrap/app.php`:
```php
->withRouting(
    web: __DIR__.'/../routes/web.php',
    api: __DIR__.'/../routes/api.php',
    commands: __DIR__.'/../routes/console.php',
)
->withMiddleware(function (Middleware $m) {
    $m->throttleApi();
})
```

---

## Middleware

| Feature | Laravel 10 | Laravel 11 | Laravel 12 |
|---------|-----------|-----------|-----------|
| Registration | `app/Http/Kernel.php` | `bootstrap/app.php` | `bootstrap/app.php` |
| Middleware Groups | `$middlewareGroups` | `withMiddleware()` | `withMiddleware()` |
| Aliases | `$middlewareAliases` | `->alias()` | `->alias()` |
| Priority | `$middlewarePriority` | No priority (auto) | Same |

**Laravel 11+ Registration**:
```php
// bootstrap/app.php
->withMiddleware(function (Middleware $m) {
    $m->web(append: [CheckAge::class]);
    $m->api(prepend: [JwtAuth::class]);
    $m->alias(['admin' => CheckAdmin::class]);
})
```

---

## Exception Handling

| Feature | Laravel 10 | Laravel 11 | Laravel 12 |
|---------|-----------|-----------|-----------|
| Handler File | `app/Exceptions/Handler.php` | `bootstrap/app.php` (inline) | `bootstrap/app.php` |
| Custom Render | `render($request, $e)` | `render($request, $e)` | Same |
| Custom Report | `report($e)` | `report($e)` | Same |

**Laravel 11+ Handler**:
```php
// bootstrap/app.php
->withExceptions(function (Exceptions $ex) {
    $ex->report(function (Throwable $e) {
        // Custom reporting
    });
    $ex->render(function (NotFoundHttpException $e) {
        return response()->json(['error' => 'Not found'], 404);
    });
})
```

---

## Console / Scheduling

| Feature | Laravel 10 | Laravel 11 | Laravel 12 |
|---------|-----------|-----------|-----------|
| Scheduler Definition | `app/Console/Kernel.php` | `routes/console.php` | `routes/console.php` |
| Kernel (artisan commands) | `app/Console/Kernel.php` | `app/Console/Commands/` (dropped Kernel) | `app/Console/Commands/` |
| Artisan Boot | `boot()` in Kernel | Auto-discovery | Auto-discovery |

**Laravel 11+ Scheduling** (`routes/console.php`):
```php
use Illuminate\Support\Facades\Schedule;

Schedule::command('emails:send')->dailyAt('09:00');
Schedule::job(new ProcessReports)->everyFiveMinutes();
```

---

## Broadcasting

| Feature | Laravel 10 | Laravel 11 | Laravel 12 |
|---------|-----------|-----------|-----------|
| Channels File | `routes/channels.php` | `routes/channels.php` | `routes/channels.php` |
| Channel Registration | `Broadcast::channel()` in channels.php | Same | Same |
| Pusher Config | `config/broadcasting.php` | `config/broadcasting.php` | Same |

---

## Configuration

| Feature | Laravel 10 | Laravel 11 | Laravel 12 |
|---------|-----------|-----------|-----------|
| Config Path | `config/` (40+ files) | `config/` (reduced) | `config/` (minimal) |
| Environment | `.env` | `.env` | `.env` |
| Bootstrap | `bootstrap/app.php` | Streamlined | Further streamlined |
| Service Providers | `config/app.php` providers | Auto-discovery | Auto-discovery |

---

## Database / Migrations

| Feature | Laravel 10 | Laravel 11 | Laravel 12 |
|---------|-----------|-----------|-----------|
| Foreign Keys | `$table->foreignId()` (7+) | Same | Same |
| Soft Deletes | `$table->softDeletes()` | Same | Same |
| Index Naming | Manual or `unique()` | Same | Same |

---

## Deprecated Features in 11+

- `laravel new --auth` (use Breeze)
- `app/Http/Kernel.php` (use `bootstrap/app.php`)
- `app/Console/Kernel.php` for scheduling (use `routes/console.php`)
- `routes/web.php` for API routes (use `routes/api.php`)
- `assertStatus()` in favor of `assertOk()` for redirects

---

## Deprecated Features in 12+

- `@php` directive (use full PHP file includes)
- `Route::matched()` callback
- `assertRedirectedTo()` (use `assertRedirect()` then `getSession()->get()`)

---

## Migration Checklist (10 → 11 → 12)

### 10 → 11
- [ ] Replace `app/Http/Kernel.php` with `bootstrap/app.php` middleware registration
- [ ] Replace `app/Console/Kernel.php` scheduling with `routes/console.php`
- [ ] Move exception handling from `Handler.php` to `bootstrap/app.php`
- [ ] Use Breeze instead of built-in `make:auth`
- [ ] Run `php artisan about` to check new config keys

### 11 → 12
- [ ] Update `laravel/framework` to `^12.0`
- [ ] Run `composer update`
- [ ] Review `php artisan about` for config changes
- [ ] Check for updated deprecation warnings in tests


Security scan verdicts — ClawScan: clean | static analysis: clean | VirusTotal: clean | SkillSpector: suspicious (MEDIUM)