diff --git a/.agents/skills/infer-conventions/SKILL.md b/.agents/skills/infer-conventions/SKILL.md new file mode 100644 index 0000000..ae4f10e --- /dev/null +++ b/.agents/skills/infer-conventions/SKILL.md @@ -0,0 +1,105 @@ +--- +name: infer-conventions +description: "Use this skill to analyze how a Laravel application is actually written and record its conventions as shared rules. Trigger when the user wants to detect, infer, document, or standardize project conventions or coding style, set up or grow `.ai/rules`, resolve mixed or conflicting patterns (e.g. \"are we using Form Requests or inline validation?\"), or onboard agents and teammates to \"how we do things here\". Covers: a systematic sweep of ~49 Laravel convention dimensions (validation, models, architecture, testing, frontend, database, API responses), open-ended house-pattern discovery, conflict reporting, and recording rules scoped to the right paths via the Boost `record-rule` MCP tool. Only run this skill when the user explicitly asks for it; never start a sweep as part of another task. Do not use for one-off code review, enforcing formatting a linter already handles, or editing `.ai/rules` files by hand." +disable-model-invocation: true +license: MIT +metadata: + author: laravel +--- + +# Infer Conventions + +Learn how this application writes Laravel, then record what you learn as durable, path-scoped rules other agents will read. You are documenting reality, not improving it. + +## Ground Rules (read before you start) + +- Consistency first. The codebase's majority style is the convention. Never judge it, never propose a "better" pattern, never record what the code should do. If the app validates inline everywhere, that is the rule, even if Form Requests would be nicer. +- Skip what an active tool produces, keep what a tool would fight. Inspect the project's Pint and Rector configuration first; a Rector transformation is tooling-owned only when its package and relevant rule or set are installed and enabled. Active tools may rewrite code toward one canonical form: `$casts` to `casts()`, `$fillable` to attributes, magic accessors to the `Attribute` class, pipe-string rules to arrays, `$signature` to `#[Signature]`, named migrations to anonymous, and many more. When the app already sits at an active tool's target form, the tool owns it, so record nothing. But when the app deliberately holds a form an active tool would refactor away, such as legacy `getXxxAttribute()` accessors the `Attribute` class would replace, no tool can reproduce that choice and an agent defaults the other way. That against-the-grain hold is exactly what to record. +- Record decisions, not defaults. A consistent pattern earns a rule only when it reflects a choice: the app took one valid option where the framework or common practice offered others, or the pattern would surprise a competent agent. Framework defaults steer nothing, so skip them: anonymous migrations, `$signature` commands, `ShouldQueue` jobs, `casts()` on Laravel 11+, named routes, Rule objects in `app/Rules`, and `Mail::fake()` or `Bus::fake()` to isolate framework services. A real fork is not enough on its own. Weigh the side the app took, and record only the side an agent would not reach for by itself: inline closures everywhere, legacy accessors, a bespoke query layer. Watch for the false fork too. "No Mockery" next to facade fakes is not a choice against Mockery, because they double different things. The test for every candidate: without this rule, would the next agent plausibly write it differently? Only "yes" earns a rule. +- Architecture choices are the gold. Record presence and deliberate absence. The structural pattern the app commits to is the highest-signal convention and the one no tool can decide: Action classes and how they are invoked (`handle` / `execute` / `__invoke`), service objects, dedicated query objects exposing `builder()`, DTOs (spatie/laravel-data vs readonly classes), Form Request validation vs inline, an events and listeners spine vs direct calls, and domain or module folders. Also record a consistent non-pattern, such as "query Eloquent directly in controllers, no repository layer", so the next agent matches the app's altitude instead of over-engineering. +- Never duplicate `.ai/rules`. Read `.ai/rules/index.md` and the area files before the sweep. A dimension already covered there is marked done and skipped. +- Evidence or silence. A convention needs at least 3 consistent examples and no meaningful rival to become a candidate. Every Step 1 verdict applies this bar. +- The recorded rule states the convention, nothing else. One or two imperative lines: this project does X, so do X here. Keep detection evidence out. No counts, ratios, current usage, file lists, or example paths, because that is proof for the confirm step, not part of the rule. One short syntax fragment at most, and point to `search-docs` for API details. + +## Process + +Each step ends on a checkable completion criterion. Do not advance until it holds. + +Fan out when you can. The sweep is embarrassingly parallel. If your environment can spawn subagents (a Task, dispatch, or equivalent tool), do Step 0 yourself, then hand each checklist group (A to J) and the architecture map to its own subagent. Each subagent runs the greps, reads a few representative files, and returns structured verdicts (dimension, verdict, evidence, proposed glob / title / note). You aggregate, dedupe, then run Steps 3 to 5. It is far faster on a real app. No subagents available? Run the steps in sequence, with the same bar and the same output. + +### Step 0: Orient + +Read `composer.json` (installed packages tell you which checklist groups apply), the `pint.json` / PHPStan / Rector config, `.ai/rules/index.md` if present, and most important, map the `app/` tree. List every directory under `app/` (and any `Modules/`, `src/`, `packages/`, or domain root). Every folder beyond Laravel's default skeleton (`Http`, `Models`, `Providers`, `Console`, `Exceptions`) is a structural pattern the app committed to and a high-value rule waiting to be written: `Actions`, `Services`, `Data` or DTOs, `Queries`, `Repositories`, `ViewModels`, `Pipelines`, `Support`, `Enums`, `Contracts`, `Observers`, or `Domain` and module roots. Note each one. You will confirm how it is used in Step 2. + +This app has no Livewire/Inertia/Flux packages installed. Treat the frontend group as likely API-only: confirm from `resources/views` before spending time there, and skip the Livewire/Inertia/Flux dimensions. + +Done when: you have the applicable checklist groups, the dimensions already recorded in `.ai/rules`, and a list of every non-default `app/` directory mapped to the pattern it represents. + +### Step 1: Predefined sweep + +Open `references/checklist.md` and work every applicable dimension using its search hints. Give each exactly one verdict: + +- Pattern. Clears the bar, rival under ~20% of sites, and reflects a real choice (passes the decisions-not-defaults test). A recording candidate. Cite 2 to 3 example files. +- Conflict. Both styles present in meaningful numbers. Report the split with counts and example files. Never record a preferred winner while the code remains mixed, even in yolo, because that would describe an aspiration rather than reality. Record only if the user identifies a stable path or context boundary that explains both styles; otherwise defer until the code is reconciled. +- Default. Consistent, but a framework or common-practice default the agent already writes unprompted. Skip it as a no-op, not a convention. +- No signal. Under the bar: feature unused, or too few examples. Skip silently (one summary line at most). +- Tooling-owned or Already-recorded. Skip per the ground rules. + +Done when: every applicable dimension carries exactly one of those verdicts. + +### Step 2: Open-ended pass + +First, close out the architecture map from Step 0. For every non-default `app/` directory you listed, confirm how the pattern is used and apply the same evidence and decisions-not-defaults tests as Step 1. Generator-standard or sparsely used directories such as `Rules`, `Observers`, `Mail`, and `Notifications` are signals to inspect, not automatic conventions. Make genuine structural patterns candidates: Action classes invoked via `handle` / `execute` / `__invoke`, Services constructor-injected, `Queries` objects exposing `builder(): Builder`, DTOs as readonly classes or spatie/laravel-data, module or domain folders as the unit of organization. Scope each qualifying pattern to its own directory glob. Also record a consistent deliberate absence, such as "no repository layer, controllers query Eloquent directly", so the next agent matches the app's altitude. + +Then find what else makes this codebase itself: base or abstract classes most code extends, traits used everywhere, tenancy or authorization scoping woven through queries, naming schemes, and custom helpers. Same evidence bar, cite files. Record every genuine structural pattern, and cap the other house findings at ~5 so the pass stays high-signal. + +Done when: every non-default `app/` directory from Step 0 has a verdict, and the pass has produced its cited house findings (or concluded there are none). + +### Step 3: Confirm + +Present every candidate in one batch. Per item: dimension, verdict, evidence (counts and files), and the exact proposed `glob` or `globs` / `title` / `note`. Conflicts are presented as questions about an existing context boundary or deferred cleanup, not as a choice of future style. + +Default mode is confirm: record only what the user approves. Switch to yolo only when the invocation said so ("yolo", "don't ask", "just record them"), then record all pattern candidates without asking. Conflicts still go to the user in yolo. + +Done when: every candidate is approved, rejected, or (conflicts) decided. + +### Step 4: Record + +Make one `record-rule` call for each glob an approved convention applies to. Choose the most specific globs that cover the cited evidence from the mapping table below; if a convention spans models and migrations, record it under both domains so agents discover it from either path. The `note` is the bare convention: strip every trace of detection (see the ground rule). If `record-rule` is unavailable (rules disabled), report the full rule text so the user can enable `BOOST_RULES_ENABLED` or add it by hand. + +Record this: + +> Accessors and mutators: use the legacy magic-method style (`getXxxAttribute()` / `setXxxAttribute()`), not the `Attribute` class. Match it in models. + +Not this: + +> Accessors/mutators use the legacy magic-method style; the `Attribute`-class style is not used anywhere (13 legacy, 0 Attribute-class), e.g. `app/Models/Post.php`. Match the legacy style in existing models. + +Done when: every approved item has a successful tool response, and any failure is reported with its rule text. + +### Step 5: Summarize + +List recorded rules (file and title), conflicts the user deferred, notable no-signals, and remind the user to commit `.ai/rules` so their team and agents share the conventions. + +## Glob mapping + +Attach each rule to the most specific path that covers its evidence. Never a lazy `app/**` when a subtree fits. Match the glob to where the code actually lives, which is not the same in a default skeleton and in a modular or DDD layout. Use the Step 0 `app/` map to pick the real path. + +Examples: + +- Models: `app/Models/**` in a default app, or `app/Modules/Blog/Models/**` / `src/Domain/Blog/**` in a modular one. +- Controllers, routing, validation, responses: `app/Http/**`, or `app/Modules/*/Http/**` when each module owns its HTTP layer. +- Actions, Services, DTOs: `app/Actions/**`, `app/Services/**`, `app/Data/**`, or the module path the app actually uses. +- Tests: `tests/**`. +- Migrations and database: `database/migrations/**`. +- Truly app-wide (rare, e.g. auth retrieval): `app/**`. + +`record-rule` takes one glob. When a convention genuinely spans two domains (e.g. UUID keys touch models and migrations), call it once per domain with the same title and note; mentioning another path in the note does not make the rule discoverable there. + +## Edge cases + +- Rules disabled or `record-rule` missing: detection is read-only, so Steps 0 to 3 still run, and recording falls back to the manual path in Step 4. +- Tiny or fresh app: most dimensions land on no-signal. Say so honestly ("not enough code to infer conventions yet") and record nothing. +- Huge app: each dimension is a bounded grep plus a handful of file reads. Sample representative files, do not read everything. +- Re-runs: reading `.ai/rules` in Step 0 makes re-runs incremental, so only new or undecided dimensions surface. +- Non-standard layout (modules, DDD): the open-ended pass catches the layout itself as convention #1. Adapt the globs in the mapping table to the observed paths. diff --git a/.agents/skills/infer-conventions/references/checklist.md b/.agents/skills/infer-conventions/references/checklist.md new file mode 100644 index 0000000..87df48c --- /dev/null +++ b/.agents/skills/infer-conventions/references/checklist.md @@ -0,0 +1,137 @@ +# Detection Checklist + +Every dimension here is a genuine fork: Laravel offers two or more valid approaches, the app's choice changes what the next agent writes, and no active project tool can pick for you. Left out on purpose: pure formatting (Pint owns it), any form an installed and enabled Rector rule rewrites to one canonical shape (`$casts` to `casts()`, `$fillable` to attributes, pipe-string rules to arrays, named to anonymous migrations, `$signature` to `#[Signature]`), and framework defaults any agent writes unprompted (`ShouldQueue` jobs, relation return types, `HasFactory`). + +Each item gives the fork, then a hint (a grep or dir to spot which side the app takes). Hints are only a start. Read the matched files, never record on a raw count. Apply the ground rules to every verdict: a consistent choice that is a default or a tool's target form is not a pattern. Rows tagged (architecture) are the highest-signal, so record presence and deliberate absence. + +--- + +## A. Validation & HTTP input + +1. Validation entry point: inline `$request->validate()` vs Form Request classes vs `Validator::make()`. + - Hint: `ls app/Http/Requests`; grep -- `->validate(` / `Validator::make(` in `app/Http/Controllers`. +2. Custom rule location: invokable rule objects in `app/Rules` vs inline closures vs `Validator::extend()` in a provider. Rule objects are the default `make:rule` path, so record only if the app leans on closures or `Validator::extend` instead. "No rule objects" alone is just no-signal. + - Hint: `ls app/Rules`; grep `Validator::extend` in `app/Providers`. +3. Typed input retrieval: typed getters (`$request->string()`, `->integer()`, `->enum()`, `->date()`) vs raw `$request->input()` / dynamic properties. + - Hint: grep -- `->string(` / `->integer(` / `->enum(` vs `->input(` in `app/Http`. +4. Custom messages/attributes: `lang/*/validation.php` vs Form Request `messages()` / `attributes()` methods. + - Hint: `ls lang`; grep `function messages`, `function attributes` in `app/Http/Requests`. + +## B. Controllers & routing + +5. Controller shape: invokable single-action (`__invoke`) vs resource controllers vs plain multi-method. + - Hint: grep `__invoke` in controllers; `Route::resource` / `apiResource` vs verb routes. +6. Business-logic location (architecture): fat controllers vs delegated to Actions / Services / Jobs. + - Hint: read a few controller methods; `ls app/Actions app/Services`. +7. Route handler style: closures in `routes/*.php` vs controller classes. + - Hint: count `function ()` vs `::class` in `routes/web.php`, `routes/api.php`. +8. Middleware assignment: route/group `->middleware()` vs controller `HasMiddleware::middleware()` vs `#[Middleware]` attribute. + - Hint: grep -- `implements HasMiddleware`, `#[Middleware(` in controllers vs `->middleware(` in routes. +9. Route model binding: implicit (type-hinted models) vs explicit `Route::bind` vs manual `findOrFail`. + - Hint: typed model params in signatures vs `findOrFail(` in controllers; grep `Route::bind`. +10. Rate limiting: named `RateLimiter::for()` + `throttle:name` vs inline `throttle:60,1`. + - Hint: grep `RateLimiter::for` in providers vs `throttle:` in route files. + +## C. Authorization + +11. Authorization home: Gates (`Gate::define`) vs Policy classes in `app/Policies`. + - Hint: `ls app/Policies`; grep `Gate::define` in `app/Providers`. +12. Authorization call site: `$this->authorize()` / `Gate::authorize()` vs `$user->can()` vs `can` middleware vs `#[Authorize]` vs `@can` in Blade. + - Hint: grep -- `authorize(`, `->can(`, `middleware('can:`, `#[Authorize(`, `@can(`. + +## D. Eloquent & models + +13. Mass assignment: `$fillable` allow-list vs `$guarded` block-list. + - Hint: grep `protected $fillable` / `protected $guarded` in `app/Models`. +14. Accessors/mutators: modern `Attribute` class vs legacy `getXxxAttribute()` / `setXxxAttribute()`. Record a legacy hold, it goes against the tool's grain. + - Hint: grep `: Attribute` / `Attribute::make` vs `function get[A-Z].*Attribute` in `app/Models`. +15. Primary keys: auto-increment vs `HasUuids` vs `HasUlids`. + - Hint: grep `HasUuids` / `HasUlids` in `app/Models`; migration `id()` vs `uuid('id')`. +16. Custom casts: dedicated `CastsAttributes` classes (`app/Casts`) vs inline `Attribute` vs built-in cast strings. + - Hint: `ls app/Casts`; grep `Cast::class`, `AsStringable::class` in models. +17. Data/query layer (architecture): Eloquent directly in controllers vs repositories vs dedicated query objects (e.g. classes exposing `builder(): Builder`). + - Hint: `ls app/Repositories app/Queries`; see where non-trivial queries are built. +18. Query scopes: local `scope`/`#[Scope]` methods vs dedicated builder classes. + - Hint: grep `function scope` / `#[Scope]` in models; `ls app/*/Builders`. +19. Model events: observers (`app/Observers`, `#[ObservedBy]`) vs `booted()` closures vs event classes. + - Hint: `ls app/Observers`; grep `booted`, `::observe`, `#[ObservedBy]`. +20. Eager-load posture: explicit per-query `->with()` vs model-level `$with` defaults. Treat `preventLazyLoading()` separately as a development guard because it can complement either posture. + - Hint: grep -- `protected $with`, `->with(`, and separately `preventLazyLoading` in `app/`. + +## E. Architecture & organization + +21. Action/Service structure (architecture): Action classes (invoked via `handle` / `execute` / `__invoke`) vs service objects vs neither. Cross-check the Step 0 `app/` map: any `Actions`/`Services`/`Pipelines`/`Jobs`-as-actions folder is this pattern, so record how it is invoked. + - Hint: `ls app/` (the whole tree, not just `Actions`/`Services`); grep the invocation method in the folder you find. +22. DTOs (architecture): spatie/laravel-data vs plain readonly classes vs arrays everywhere. + - Hint: `ls app/Data`; grep `extends Data`, `readonly class` in `app/`. +23. Dependency acquisition: constructor/method injection vs `app()` / `resolve()` / `App::make()` service location. + - Hint: grep `app(` / `resolve(` / `::make(` in `app/` vs promoted constructor deps. +24. Decoupling: events + listeners vs direct service calls. + - Hint: `ls app/Events app/Listeners`; grep `event(`, `::dispatch(`. +25. Helper vs facade idiom: global helpers (`config()`, `auth()`, `response()`) vs facades (`Config::`, `Auth::`, `Response::`). + - Hint: ratio of `config(` vs `Config::` (etc.) across `app/`. +26. Namespace layout (architecture): default `app/` skeleton vs domain/module folders (`app/Domain/**`, modules). + - Hint: `ls app/`, look for `Domain/`, `Modules/`, bounded-context folders. +27. Enums: backed vs pure; case naming; where they live. + - Hint: `ls app/Enums`; grep `enum .*: string`, `enum .*: int`. + +## F. Frontend & views + +No Livewire/Inertia/Flux package is installed. This app may be API-only. Confirm from `resources/views` before sweeping, and treat the Livewire/Flux dimensions as not applicable. + +28. Frontend stack: Blade+Livewire vs Inertia (Vue/React/Svelte) vs Blade-only / API + separate SPA. + - Hint: `composer.json` + `package.json`; `ls resources/js/pages`, `resources/views`. +29. Blade composition: class `` components vs anonymous components (`@props`) vs `@include` partials. + - Hint: `ls app/View/Components`; grep `constrained()` vs `foreignIdFor(Model::class)` vs manual `foreign()->references()->on()`. + - Hint: grep -- `foreignId(`, `foreignIdFor(`, `->foreign(` in `database/migrations`. +34. `down()` methods: real reverse logic vs omitted / one-way migrations. + - Hint: grep `function down` vs the migration count. +35. Enum storage: DB `enum()` column vs `string()` + PHP-enum cast on the model. + - Hint: grep -- `->enum(` in migrations vs string columns cast to enums. +36. Transactions: `DB::transaction(fn ...)` closure vs manual `beginTransaction` / `commit` / `rollBack`. + - Hint: grep `DB::transaction`, `beginTransaction` in `app/`. +37. Idempotent writes: `upsert` / `updateOrCreate` / `firstOrCreate` vs find-then-save. + - Hint: grep `upsert(`, `updateOrCreate(`, `firstOrCreate(` in `app/`. + +## H. Testing + +38. Framework: Pest (`it()` / `test()` / `expect()`) vs PHPUnit classes. + - Hint: `ls tests/Pest.php`; grep `it(` / `test(` vs `extends TestCase`. +39. DB reset: `RefreshDatabase` vs `DatabaseTruncation` vs `DatabaseMigrations`. + - Hint: grep those trait names in `tests/`. +40. Fixtures: compare how equivalent test-owned records are created, such as factories vs manual inserts. Track seeders separately for shared reference data because `$this->seed()` commonly and legitimately coexists with factories. + - Hint: grep `::factory(` and direct inserts in `tests/`; separately inspect `$this->seed(` calls and what those seeders provide. +41. Collaborator isolation: how the app doubles its own classes, Mockery `mock()` / `spy()` vs real integration. Ignore facade fakes like `Mail::fake()` here, they isolate framework services by default and are not a fork against Mockery. + - Hint: grep -- `->mock(`, `->spy(`, `Mockery::` in `tests/`. +42. Endpoint assertions: array `assertJson([...])` / `assertJsonFragment` vs fluent `AssertableJson`. + - Hint: grep `AssertableJson`, `assertJsonFragment` in `tests/`. + +## I. Responses & API resources + +43. Response shape: API Resource classes vs `response()->json()` vs returning models/arrays directly. + - Hint: `ls app/Http/Resources`; grep -- `JsonResource`, `->json(` in controllers. +44. Resource relationship inclusion: `whenLoaded()` guards vs unconditional relationship access. Do not count ordinary scalar attributes as rivals to conditional relationships, and evaluate general `when()` fields separately. + - Hint: compare relationship fields using `whenLoaded(` with unconditional relationship property access in `app/Http/Resources`. +45. Pagination contracts: within comparable endpoint categories, length-aware `paginate()` vs `simplePaginate()` vs `cursorPaginate()`. These have different totals, navigation, ordering, and performance contracts, so record only a stable path-scoped API policy, never a project-wide majority. + - Hint: grep those in `app/`, then group matches by endpoint type and client contract before comparing them. +46. Web redirects/URLs: `route('name')` vs `url('/path')` vs `action([...])`. + - Hint: grep `route('`, `url('/`, `action([` in `app/Http` and views. + +## J. Strings, collections & dates + +47. Iteration idiom: `collect()->map()->filter()` pipelines vs `array_map` / `foreach`. + - Hint: grep -- `collect(`, `->map(` vs `array_map`, `foreach` density in `app/`. +48. String API: fluent `Str::of()->...` (Stringable) vs static `Str::` vs native (`trim`, `strtoupper`). + - Hint: grep `Str::of(` vs `Str::` vs native string funcs. +49. Dates: compare equivalent construction call styles (`now()` / `today()` helpers vs `Carbon::`) separately from the application's mutable/immutable date policy. `Date::use(CarbonImmutable::class)` can make helpers return immutable dates, so those signals are complementary rather than conflicting. + - Hint: grep `now(` and `Carbon::` for call style; separately inspect `CarbonImmutable` and `Date::use` for mutability policy. + +--- + +Genuine forks only. Every row survived the "no tool can decide this, and it isn't the default" filter. Give each applicable dimension exactly one verdict: pattern, conflict, default, no-signal, tooling-owned, or already-recorded. The rows tagged (architecture) are where the highest-value rules come from. diff --git a/.agents/skills/laravel-best-practices/SKILL.md b/.agents/skills/laravel-best-practices/SKILL.md new file mode 100644 index 0000000..311ab84 --- /dev/null +++ b/.agents/skills/laravel-best-practices/SKILL.md @@ -0,0 +1,59 @@ +--- +name: laravel-best-practices +description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns." +license: MIT +metadata: + author: laravel +--- + +# Laravel Best Practices + +Best practices for Laravel, organized as an index of rule files. Each rule file teaches what to do and why. For exact API syntax, verify with `search-docs`. + +## Consistency First + +Before applying any rule, check what the application already does. Laravel offers multiple valid approaches, and the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern. + +Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it. Don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides. + +## How to Apply + +1. Check the changed files, nearby code, project configuration, and relevant tests for established patterns. Deviate only for a correctness or security defect, and call the deviation out. +2. Map every affected concern to the rule index below. Read each mapped rule file before editing. Skip unrelated rule files. +3. Make the smallest coherent change. Keep the application's architecture and naming instead of introducing a second pattern for the same job. +4. Verify version-sensitive Laravel APIs for the installed version with `search-docs`, or inspect the installed framework when it is unavailable. +5. Run the narrowest relevant tests first, then the project's formatting and static-analysis checks when the change warrants them. +6. Re-read the diff against every mapped rule before finishing. + +## Rule Index + +Cross-cutting changes often need more than one rule file. + +| Concern | Read | +| --- | --- | +| Query count, eager loading, indexes, large datasets | [`rules/db-performance.md`](rules/db-performance.md) | +| Subqueries, aggregates, complex ordering and query plans | [`rules/advanced-queries.md`](rules/advanced-queries.md) | +| Models, relationships, scopes, casts | [`rules/eloquent.md`](rules/eloquent.md) | +| Authentication, authorization, input safety, secrets, uploads | [`rules/security.md`](rules/security.md) | +| Form Requests and validation rules | [`rules/validation.md`](rules/validation.md) | +| Controllers, route binding, resources, middleware | [`rules/routing.md`](rules/routing.md) | +| Schema changes, columns, foreign keys, indexes | [`rules/migrations.md`](rules/migrations.md) | +| Jobs, retries, uniqueness, batches, Horizon | [`rules/queue-jobs.md`](rules/queue-jobs.md) | +| Cache lifetime, invalidation, locks, memoization | [`rules/caching.md`](rules/caching.md) | +| Outbound requests, retries, timeouts, fakes | [`rules/http-client.md`](rules/http-client.md) | +| Exceptions, reporting, rendering, log context | [`rules/error-handling.md`](rules/error-handling.md) | +| Events and notifications | [`rules/events-notifications.md`](rules/events-notifications.md) | +| Mailables and mail assertions | [`rules/mail.md`](rules/mail.md) | +| Scheduled tasks and overlap protection | [`rules/scheduling.md`](rules/scheduling.md) | +| Collections, lazy iteration, bulk operations | [`rules/collections.md`](rules/collections.md) | +| Blade components, attributes, composers | [`rules/blade-views.md`](rules/blade-views.md) | +| Environment values and application configuration | [`rules/config.md`](rules/config.md) | +| Tests: coverage, factories, fakes, and assertions | the `testing-best-practices` skill | +| Naming, helpers, file boundaries, PHP style | [`rules/style.md`](rules/style.md) | +| Actions, services, dependencies, application structure | [`rules/architecture.md`](rules/architecture.md) | + +## Decision Rules + +- Prefer framework features and existing application abstractions over new helpers or dependencies. +- Avoid speculative abstractions. Extract code when it creates a clear domain boundary, removes meaningful duplication, or makes behavior independently testable. +- Keep database access out of Blade views and prevent hidden N+1 queries across controllers, resources, jobs, and serialization. diff --git a/.agents/skills/laravel-best-practices/rules/advanced-queries.md b/.agents/skills/laravel-best-practices/rules/advanced-queries.md new file mode 100644 index 0000000..54dd783 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/advanced-queries.md @@ -0,0 +1,106 @@ +# Advanced Query Best Practices + +## Select Single Relationship Values with Subqueries + +When only one value from a has-many relationship is needed, consider a correlated subquery with `addSelect()` instead of loading the entire relationship. This selects the value as part of the main query without an additional relationship query. + +```php +public function scopeWithLastLoginAt($query): void +{ + $query->addSelect([ + 'last_login_at' => Login::select('created_at') + ->whereColumn('user_id', 'users.id') + ->latest() + ->take(1), + ])->withCasts(['last_login_at' => 'datetime']); +} +``` + +## Create Dynamic Relationships with a Subquery Foreign Key + +The same pattern can select a foreign key and expose the selected model through a `belongsTo` relationship. Eager loading that relationship still executes a separate query, but it avoids loading the full has-many collection. + +```php +public function lastLogin(): BelongsTo +{ + return $this->belongsTo(Login::class, 'last_login_id'); +} + +public function scopeWithLastLogin($query): void +{ + $query->addSelect([ + 'last_login_id' => Login::select('id') + ->whereColumn('user_id', 'users.id') + ->latest() + ->take(1), + ])->with('lastLogin'); +} +``` + +## Combine Related Counts with Conditional Aggregates + +Combine several counts over the same filtered data set into one query by using conditional aggregates. Use `toBase()` when only scalar values are needed and model hydration provides no benefit. Confirm the expression syntax against the application's database engine. + +```php +$statuses = Feature::toBase() + ->selectRaw("count(case when status = 'Requested' then 1 end) as requested") + ->selectRaw("count(case when status = 'Planned' then 1 end) as planned") + ->selectRaw("count(case when status = 'Completed' then 1 end) as completed") + ->first(); +``` + +## Reuse Loaded Parent Models with `setRelation()` + +When a parent and its children are already loaded and code also accesses `$child->parent`, set the inverse relationship to the existing parent instance. This avoids an additional lazy-loading query for each child. + +```php +$feature->load('comments.user'); +$feature->comments->each->setRelation('feature', $feature); +``` + +## Compare `whereHas()` with an `IN` Subquery + +`whereHas()` typically produces an `EXISTS` subquery, while `whereIn()` can express the same filter with an `IN` subquery. Either form may be faster depending on the database engine, indexes, cardinality, and query plan. Measure both forms with representative data; neither subquery loads its result set into PHP memory. + +Option using `EXISTS`: + +```php +$query->whereHas('company', fn ($q) => $q->where('name', 'like', $term)); +``` + +Option using `IN`: + +```php +$query->whereIn('company_id', Company::where('name', 'like', $term)->select('id')); +``` + +## Measure Two Simple Queries Against One Complex Query + +Two targeted queries can outperform one complex correlated subquery or join when the first query is highly selective. They also add a database round trip, can transfer a large identifier list, and do not provide a single-query consistency snapshot. Decide from query plans and production-like measurements. + +## Design Composite Indexes for the Query + +For common multi-column sorts, consider a composite index whose column order supports the query's filters and ordering. Database engines may combine indexes or choose an explicit sort, so matching the `ORDER BY` list alone does not guarantee that an index will be used. Verify the query plan. + +```php +// Migration +$table->index(['last_name', 'first_name']); + +// Query that this index may support +User::query()->orderBy('last_name')->orderBy('first_name')->paginate(); +``` + +## Consider a Correlated Subquery for Has-Many Ordering + +When sorting by one value from a has-many relationship, a direct join can duplicate parent rows unless it first reduces the related table to one row per parent. A correlated subquery in `orderBy()` is often simpler, but its performance depends on the query plan and supporting indexes. + +```php +public function scopeOrderByLastLogin($query): void +{ + $query->orderByDesc(Login::select('created_at') + ->whereColumn('user_id', 'users.id') + ->latest() + ->take(1) + ); +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/architecture.md b/.agents/skills/laravel-best-practices/rules/architecture.md new file mode 100644 index 0000000..d0a9a55 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/architecture.md @@ -0,0 +1,219 @@ +# Architecture Best Practices + +## Extract Focused Business Operations + +Extract a discrete business operation into an action class when doing so makes the operation easier to reuse or test. An action class has no special meaning to Laravel; follow the project's naming and invocation conventions. + +```php +class CreateOrderAction +{ + public function __construct(private InventoryService $inventory) {} + + public function handle(array $data): Order + { + $order = Order::create($data); + $this->inventory->reserve($order); + + return $order; + } +} +``` + +## Inject Required Dependencies + +Prefer constructor injection for dependencies required throughout an object's lifetime. Method injection is appropriate for dependencies needed by one controller action, listener, job handler, or other container-invoked method. Avoid `app()` and `resolve()` when normal injection can make a dependency explicit. + +Hidden dependency: + +```php +class OrderController extends Controller +{ + public function store(StoreOrderRequest $request) + { + $service = app(OrderService::class); + + return $service->create($request->validated()); + } +} +``` + +Injected dependency: + +```php +class OrderController extends Controller +{ + public function store(StoreOrderRequest $request, OrderService $service) + { + return $service->create($request->validated()); + } +} +``` + +## Depend on Contracts at Boundaries + +Depend on contracts at system boundaries, such as payment gateways, notification channels, and external services, when testability or interchangeable implementations justify the abstraction. + +Concrete boundary dependency: + +```php +class OrderService +{ + public function __construct(private StripeGateway $gateway) {} +} +``` + +Contract boundary dependency: + +```php +interface PaymentGateway +{ + public function charge(int $amount, string $customerId): PaymentResult; +} + +class OrderService +{ + public function __construct(private PaymentGateway $gateway) {} +} +``` + +Bind in a service provider: + +```php +$this->app->bind(PaymentGateway::class, StripeGateway::class); +``` + +## Specify a Deterministic Sort Order + +Without an explicit `ORDER BY`, row order is undefined. Choose an order that matches the feature, and add a unique tie-breaker when stable pagination matters. + +Unspecified order: + +```php +$posts = Post::paginate(); +``` + +Newest first with a stable tie-breaker: + +```php +$posts = Post::query() + ->orderByDesc('created_at') + ->orderByDesc('id') + ->paginate(); +``` + +## Use Atomic Locks for Race Conditions + +Use a lock when concurrent execution must be serialized. `Cache::lock()` provides an atomic lock when the configured cache store supports locks. `lockForUpdate()` locks selected database rows and must run inside a database transaction. These mechanisms solve different coordination problems. Set the lease (`10` below) longer than the callback can ever run: once it expires, another process can acquire the lock while the first is still working. + +```php +Cache::lock('order-processing-'.$order->id, 10)->block(5, function () use ($order) { + $order->process(); +}); + +// Or at query level, inside a transaction +DB::transaction(function () use ($id) { + $product = Product::where('id', $id)->lockForUpdate()->first(); + + // Read and update the product while the database lock is held. +}); +``` + +## Use `mb_*` String Functions + +When no Laravel helper exists, prefer multibyte-aware functions such as `mb_strlen()` and `mb_strtolower()` for UTF-8 text. For example, `strlen()` counts bytes, while `strtolower()` is not multibyte-aware. + +Incorrect: + +```php +strlen('José'); // 5 bytes, not 4 characters +strtolower('MÜNCHEN'); // Does not lowercase Ü +``` + +Correct: + +```php +mb_strlen('José'); // 4 characters +mb_strtolower('MÜNCHEN'); // 'münchen' + +// Prefer Laravel's Str helpers when available +Str::length('José'); // 4 +Str::lower('MÜNCHEN'); // 'münchen' +``` + +## Use `defer()` for Post-Response Work + +For lightweight work that does not need retries or crash durability, consider `defer()` instead of dispatching a job. During an HTTP request, the callback normally runs after the response has been sent but remains in the same PHP process. + +Queued and durable: + +```php +dispatch(new LogPageView($page)); +``` + +Deferred in the current process: + +```php +defer(fn () => PageView::create(['page_id' => $page->id, 'user_id' => auth()->id()])); +``` + +Use a queued job when the work needs retries, queue controls, or durability across process failures. + +## Use `Context` for Request-Scoped Data + +The `Context` facade makes contextual data available across the current execution lifecycle without manually passing arguments through every layer. + +```php +// In middleware +Context::add('tenant_id', $request->header('X-Tenant-ID')); + +// Later in the same execution lifecycle +$tenantId = Context::get('tenant_id'); +``` + +Visible context is added to log context, and both visible and hidden context are captured and restored for queued jobs. Use `Context::addHidden()` for data that should propagate to queued jobs without appearing in logs. Do not place secrets in context unless that propagation is intended. + +## Use `Concurrency::run()` for Parallel Execution + +Run independent operations concurrently through Laravel's configured concurrency driver. + +```php +use Illuminate\Support\Facades\Concurrency; + +[$users, $orders] = Concurrency::run([ + fn () => User::count(), + fn () => Order::where('status', 'pending')->count(), +]); +``` + +With a process-based driver, each closure runs in a separate PHP process that boots the application. Use concurrency when independent database queries, HTTP client calls, or computations benefit enough to offset process and serialization overhead. The `sync` driver executes closures sequentially and is useful primarily during testing. + +## Follow Framework Conventions + +Follow Laravel conventions unless the domain or an existing schema requires an override. + +Customized schema: + +```php +class Customer extends Model +{ + protected $table = 'Customer'; + protected $primaryKey = 'customer_id'; + + public function roles(): BelongsToMany + { + return $this->belongsToMany(Role::class, 'role_customer', 'customer_id', 'role_id'); + } +} +``` + +Conventional schema: + +```php +class Customer extends Model +{ + public function roles(): BelongsToMany + { + return $this->belongsToMany(Role::class); + } +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/blade-views.md b/.agents/skills/laravel-best-practices/rules/blade-views.md new file mode 100644 index 0000000..4ea2c6c --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/blade-views.md @@ -0,0 +1,36 @@ +# Blade and View Best Practices + +## Use `$attributes->merge()` in Component Templates + +Use the component attribute bag so callers can add attributes. `merge()` combines default attributes with caller-provided values; class values receive special merging behavior. + +```blade +
merge(['class' => 'alert alert-'.$type]) }}> + {{ $message }} +
+``` + +## Use `@pushOnce` for Per-Component Scripts + +If a component renders repeatedly, `@push` adds its script on every render. Use a consistently named `@pushOnce` block to add that content once per rendered response. + +## Prefer Components for Explicit Interfaces + +Use a Blade component when a reusable interface benefits from explicit props, an attribute bag, or slots. An include remains suitable for a small partial that intentionally uses the current view data; pass an explicit data array when implicit variable sharing would obscure its dependencies. + +## Share Compatible View Data with a View Composer + +Use a view composer to centralize data needed whenever one or more named Blade views are rendered. Keep the composer compatible with every view it targets, and avoid broad wildcards when views require different data shapes. A view composer runs when Laravel renders the matching view; it does not supply data to JSON, streamed, or other non-view responses. + +## Return Blade Fragments for Partial Rendering + +A route can return either a full view or a named fragment for clients such as htmx or Turbo. + +```php +return view('dashboard', compact('users')) + ->fragmentIf($request->hasHeader('HX-Request'), 'user-list'); +``` + +## Share Parent Component Props with `@aware` + +Use `@aware` when a nested component needs a prop explicitly passed to an ancestor component. It does not expose an ancestor's default prop value unless that value was passed through the attribute bag. diff --git a/.agents/skills/laravel-best-practices/rules/caching.md b/.agents/skills/laravel-best-practices/rules/caching.md new file mode 100644 index 0000000..cd2ffd6 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/caching.md @@ -0,0 +1,100 @@ +# Caching Best Practices + +## Use `Cache::remember()` for Cache-Aside Reads + +`Cache::remember()` implements a cache-aside read without a separate truthiness check. It does not prevent concurrent requests from computing the same missing value; use an atomic lock when duplicate computation must be prevented. + +The manual version below incorrectly treats valid falsy values, such as `false` or `0`, as cache misses. + +Incorrect: + +```php +$val = Cache::get('stats'); +if (! $val) { + $val = $this->computeStats(); + Cache::put('stats', $val, 60); +} +``` + +Correct: + +```php +$val = Cache::remember('stats', 60, fn () => $this->computeStats()); +``` + +## Consider `Cache::flexible()` for Stale-While-Revalidate + +For frequently read keys, `Cache::flexible()` can serve stale data during a defined stale period and register a deferred refresh. During an HTTP request, that refresh normally runs after the response; it is not a durable background job. Once the stale period has elapsed, the request recomputes the value synchronously. + +Synchronous expiration: + +```php +Cache::remember('users', 300, fn () => User::all()); +``` + +Stale-while-revalidate tradeoff: + +```php +Cache::flexible('users', [300, 600], fn () => User::all()); +``` + +This value is fresh for five minutes and may be served stale until ten minutes after it was cached. + +## Use `Cache::memo()` to Avoid Redundant Hits Within an Execution + +If the same cache key is read repeatedly during one request or job, `memo()` decorates a cache store and retains resolved values in memory for that execution. + +```php +$settings = Cache::memo()->get('settings'); +``` + +Repeated reads through the same memoized store avoid additional store lookups. Writes through the memoized store update or invalidate its in-memory values as appropriate. + +## Use Cache Tags to Invalidate Related Groups + +Tags group related entries for invalidation without tracking each key. Cache tags are not supported by the `file`, `dynamodb`, or `database` drivers; confirm support before choosing a store. + +```php +Cache::tags(['user-1'])->flush(); +``` + +## Use `Cache::add()` for Atomic Conditional Writes + +`add()` atomically writes a value only when the key does not already exist. + +Incorrect: + +```php +if (! Cache::has('lock')) { + Cache::put('lock', true, 10); +} +``` + +Correct: + +```php +Cache::add('lock', true, 10); +``` + +Use `Cache::lock()` rather than an ordinary cache key when lock ownership and safe release are required. + +## Use `once()` for In-Process Memoization + +`once()` memoizes a callback's return value for the current request or job. Calls made from an object instance are scoped to that instance. Unlike `Cache::memo()`, `once()` does not read from an external cache store. + +```php +public function roles(): Collection +{ + return once(fn () => $this->loadRoles()); +} +``` + +Repeated calls return the memoized result without rerunning the callback. Use `once()` for repeated computation within one execution. Use `Cache::memo()` to memoize access to an underlying store that can also persist values across executions. + +## Configure Failover Cache Stores in Production + +The failover driver tries each configured store in order when a store operation throws an exception. It does not consult later stores for an ordinary cache miss, and data is not replicated between stores. + +```php +'failover' => ['driver' => 'failover', 'stores' => ['redis', 'database']], +``` diff --git a/.agents/skills/laravel-best-practices/rules/collections.md b/.agents/skills/laravel-best-practices/rules/collections.md new file mode 100644 index 0000000..211fec1 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/collections.md @@ -0,0 +1,72 @@ +# Collection Best Practices + +## Use Higher-Order Messages for Simple Operations + +Explicit closure: + +```php +$users->each(function (User $user) { + $user->markAsVip(); +}); +``` + +Concise equivalent: + +```php +$users->each->markAsVip(); +``` + +Higher-order messages are available for supported collection methods such as `each`, `map`, `filter`, and `sum`. Use an explicit closure when arguments or nontrivial logic would be clearer. + +## Choose Between `cursor()` and `lazy()` + +`cursor()` executes one query and hydrates models individually, but it cannot eager load relationships. The database driver's result buffering can still consume substantial memory for very large results. Use it for low-memory, attribute-only iteration when one long-running query is acceptable. + +`lazy()` executes multiple chunked queries and returns a flat `LazyCollection`. It supports eager loading relationships for each chunk and avoids holding one database cursor open for the entire iteration. + +With relationships: + +```php +User::with('roles')->lazy()->each(function (User $user) { + // The roles for this chunk have been eager loaded. +}); +``` + +Without relationships: + +```php +User::cursor()->each(function (User $user) { + // Process model attributes. +}); +``` + +## Use `lazyById()` When Updating Records While Iterating + +`lazy()` uses offset pagination, so updates to columns that affect the query can shift rows and cause records to be skipped or processed twice. `lazyById()` paginates by a monotonic key and is safer when updating other columns during iteration. Do not change the pagination key itself while iterating. + +## Use `toQuery()` for Bulk Operations on Collections + +Use `toQuery()` to build a query from the models in an Eloquent collection instead of manually constructing a `whereIn` clause. + +Manual query: + +```php +User::whereIn('id', $users->modelKeys())->update(['active' => false]); +``` + +Collection query: + +```php +$users->toQuery()->update(['active' => false]); +``` + +`toQuery()` requires a non-empty Eloquent collection whose models are of the same type. Like other bulk Eloquent updates, it does not dispatch per-model update events, so use it only when those events are not required. + +## Use `#[CollectedBy]` for Custom Collection Classes + +The `#[CollectedBy]` attribute declares the custom collection class without requiring a `newCollection()` override. + +```php +#[CollectedBy(UserCollection::class)] +class User extends Model {} +``` diff --git a/.agents/skills/laravel-best-practices/rules/config.md b/.agents/skills/laravel-best-practices/rules/config.md new file mode 100644 index 0000000..82691c4 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/config.md @@ -0,0 +1,85 @@ +# Configuration Best Practices + +## Read Environment Variables in Configuration Files + +Call `env()` only from configuration files. After configuration is cached, Laravel does not load the application's `.env` file, so application code should read configuration values through `config()`. + +Incorrect: + +```php +$key = env('API_KEY'); +``` + +Correct: + +```php +// config/services.php +return [ + 'key' => env('API_KEY'), +]; + +// Application code +$key = config('services.key'); +``` + +## Protect Production Secrets + +Do not commit plaintext production secrets. Laravel can encrypt an environment file so its encrypted form can be stored safely, while deployment platforms can supply secrets through their native secret stores. + +Incorrect: + +```bash +# A plaintext .env file committed to the repository +STRIPE_SECRET= +AWS_SECRET_ACCESS_KEY= +``` + +Encrypted environment file: + +```bash +php artisan env:encrypt --env=production --readable +php artisan env:decrypt --env=production +``` + +For hosted deployments, consider the platform's native secret store, such as AWS Secrets Manager or Vault, and inject secrets at runtime. + +## Use `App::environment()` for Environment Checks + +Incorrect: + +```php +if (env('APP_ENV') === 'production') { + // ... +} +``` + +Correct: + +```php +if (app()->isProduction()) { + // ... +} + +if (App::environment('production')) { + // ... +} +``` + +## Name Repeated Domain Values + +Use an enum or class constant when a domain value is repeated or represents a constrained set. A one-off string literal does not always need a named constant. + +```php +// Repeated literal +return $this->type === 'normal'; + +// Named domain value +return $this->type === self::TYPE_NORMAL; +``` + +If the application supports localization, put user-facing strings in language files and retrieve them with `__()`. Simple literals are reasonable for applications that intentionally do not support multiple languages. + +```php +// In a localized application +return back()->with('message', __('app.article_added')); +``` diff --git a/.agents/skills/laravel-best-practices/rules/db-performance.md b/.agents/skills/laravel-best-practices/rules/db-performance.md new file mode 100644 index 0000000..3f33977 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/db-performance.md @@ -0,0 +1,189 @@ +# Database Performance Best Practices + +## Eager Load Relationships Before Iterating + +When a relationship will be accessed for many models, eager load it with `with()` to avoid running one initial query plus one relationship query per model, commonly called an N+1 query pattern. Lazy loading is reasonable when the relationship may not be needed or only one model is involved. + +Lazy-loaded version: + +```php +$posts = Post::all(); +foreach ($posts as $post) { + echo $post->author->name; +} +``` + +Eager-loaded version: + +```php +$posts = Post::with('author')->get(); +foreach ($posts as $post) { + echo $post->author->name; +} +``` + +Constrain eager loads when large columns are unnecessary. Include the related model's primary key and every column Eloquent needs to match the relationship. In this example, `users.id` and `posts.user_id` match posts to users, while selecting `posts.id` preserves each related model's primary key: + +```php +$users = User::with(['posts' => function ($query) { + $query->select('id', 'user_id', 'title') + ->where('published', true) + ->latest() + ->limit(10); +}])->get(); +``` + +## Prevent Lazy Loading in Development + +Enable this in `AppServiceProvider::boot()` to catch N+1 issues during development. + +```php +public function boot(): void +{ + Model::preventLazyLoading(! app()->isProduction()); +} +``` + +By default, accessing an unloaded relationship then throws a `LazyLoadingViolationException`. Applications can customize violation handling with `handleLazyLoadingViolationUsing()`. + +## Select Only Needed Columns + +Select only the columns the operation needs when omitting large text, binary, or JSON columns provides a meaningful benefit. + +All columns: + +```php +$posts = Post::with('author')->get(); +``` + +Selected columns: + +```php +$posts = Post::select('id', 'title', 'user_id', 'created_at') + ->with(['author:id,name,avatar']) + ->get(); +``` + +When limiting selected columns, retain every key Eloquent needs for matching. A `belongsTo` relationship needs its foreign key on the parent query and the owner's key on the related query. A `hasMany` relationship needs the parent's local key and the related model's foreign key. + +## Process Large Data Sets Incrementally + +Use chunking or lazy iteration when loading an entire result set would exceed the application's practical memory budget. + +Loads the complete result set: + +```php +$users = User::all(); +foreach ($users as $user) { + $user->notify(new WeeklyDigest); +} +``` + +Processes bounded chunks: + +```php +User::where('subscribed', true)->chunk(200, function ($users) { + foreach ($users as $user) { + $user->notify(new WeeklyDigest); + } +}); +``` + +Use `chunkById()` when updates can change which rows match the query. Standard `chunk()` uses offset pagination, whose result positions can shift as rows change: + +```php +User::where('active', false)->chunkById(200, function ($users) { + $users->each->delete(); +}); +``` + +For read-only, attribute-only iteration, `cursor()` hydrates models individually from one query, although some database drivers still buffer raw results. Use `lazy()` when relationships must be eager loaded in chunks, and use `lazyById()` or `chunkById()` when updates can affect query membership. See the collection rules for detailed tradeoffs. + +## Add Indexes for Measured Query Patterns + +Design indexes around frequent, performance-sensitive query patterns. A column's presence in `WHERE`, `ORDER BY`, `JOIN`, or `GROUP BY` does not by itself justify an index; selectivity, write cost, existing indexes, and the database query plan all matter. + +Schema without an application-specific query index: + +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->constrained(); + $table->string('status'); + $table->timestamps(); +}); +``` + +Schema optimized for `WHERE status = ? ORDER BY created_at`: + +```php +Schema::create('orders', function (Blueprint $table) { + $table->id(); + $table->foreignId('user_id')->constrained(); + $table->string('status'); + $table->timestamps(); + $table->index(['status', 'created_at']); +}); +``` + +Confirm composite index column order and effectiveness with production-like data and the database's query-plan tools. Also check whether the database already created an index to support a foreign key before adding another one. + +## Count Relationships Without Loading Them + +Use `withCount()` when only relationship counts are needed; loading and hydrating every related model wastes memory. + +Loads related models: + +```php +$posts = Post::all(); +foreach ($posts as $post) { + echo $post->comments->count(); +} +``` + +Selects relationship counts: + +```php +$posts = Post::withCount('comments')->get(); +foreach ($posts as $post) { + echo $post->comments_count; +} +``` + +Conditional counting: + +```php +$posts = Post::withCount([ + 'comments', + 'comments as approved_comments_count' => function ($query) { + $query->where('approved', true); + }, +])->get(); +``` + +## Keep Queries Out of Blade Templates + +Prepare data before rendering a Blade template, such as in a controller, query service, or view composer. This keeps query behavior visible and testable. + +Query in the template: + +```blade +@foreach (User::all() as $user) + {{ $user->profile->name }} +@endforeach +``` + +Data prepared before rendering: + +```php +// Controller +$users = User::with('profile')->get(); + +return view('users.index', compact('users')); +``` + +```blade +@foreach ($users as $user) + {{ $user->profile->name }} +@endforeach +``` diff --git a/.agents/skills/laravel-best-practices/rules/eloquent.md b/.agents/skills/laravel-best-practices/rules/eloquent.md new file mode 100644 index 0000000..5a89510 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/eloquent.md @@ -0,0 +1,158 @@ +# Eloquent Best Practices + +## Define Precise Relationship Types + +Define the relationship that matches the database association, and declare its concrete return type. + +```php +public function comments(): HasMany +{ + return $this->hasMany(Comment::class); +} + +public function author(): BelongsTo +{ + return $this->belongsTo(User::class, 'user_id'); +} +``` + +## Use Local Scopes for Reusable Queries + +Extract reusable query constraints into local scopes to avoid duplication. + +Duplicated constraints: + +```php +$active = User::where('verified', true)->whereNotNull('activated_at')->get(); +$articles = Article::whereHas('user', function ($q) { + $q->where('verified', true)->whereNotNull('activated_at'); +})->get(); +``` + +Reusable local scope: + +```php +#[Scope] +protected function active(Builder $query): Builder +{ + return $query->where('verified', true)->whereNotNull('activated_at'); +} + +// Usage +$active = User::active()->get(); +$articles = Article::whereHas('user', fn ($q) => $q->active())->get(); +``` + +## Apply Global Scopes Sparingly + +Global scopes silently modify every query on the model, making debugging difficult. Prefer local scopes and reserve global scopes for truly universal constraints like soft deletes or multi-tenancy. + +Global scope tradeoff: + +```php +class PublishedScope implements Scope +{ + public function apply(Builder $builder, Model $model): void + { + $builder->where('published', true); + } +} + +// Admin panels, reports, and jobs now omit drafts unless the scope is removed. +``` + +Explicit local scope: + +```php +#[Scope] +protected function published(Builder $query): Builder +{ + return $query->where('published', true); +} + +Post::published()->paginate(); // Explicit +Post::paginate(); // Admin sees all +``` + +## Define Attribute Casts + +Use the `casts()` method (or `$casts` property following project convention) for automatic type conversion. + +```php +protected function casts(): array +{ + return [ + 'is_active' => 'boolean', + 'metadata' => 'array', + 'total' => 'decimal:2', + ]; +} +``` + +## Cast Date and Time Attributes + +Cast a date or timestamp attribute when application code should treat it as a Carbon instance. Eloquent already casts the conventional `created_at` and `updated_at` timestamps. + +Manual parsing in the template: + +```blade +{{ Carbon::parse($order->ordered_at)->toDateString() }} +``` + +Model cast: + +```php +protected function casts(): array +{ + return [ + 'ordered_at' => 'datetime', + ]; +} +``` + +```blade +{{ $order->ordered_at->toDateString() }} +{{ $order->ordered_at->format('m-d') }} +``` + +## Use `whereBelongsTo()` for Relationship Queries + +`whereBelongsTo()` expresses the relationship constraint without manually specifying its foreign key. + +Foreign key constraint: + +```php +Post::where('user_id', $user->id)->get(); +``` + +Relationship-aware constraint: + +```php +Post::whereBelongsTo($user)->get(); +Post::whereBelongsTo($user, 'author')->get(); +``` + +## Keep Application Queries Model-Aware + +Prefer Eloquent models and relationships for model-backed application queries. They preserve casts, scopes, and model table configuration. The query builder and raw SQL legitimately require table names, so use them when their lower-level behavior is intentional. + +Lower-level alternatives: + +```php +DB::table('users')->where('active', true)->get(); + +$query->join('companies', 'companies.id', '=', 'users.company_id'); + +DB::select('SELECT * FROM orders WHERE status = ?', ['pending']); +``` + +Model-aware queries: + +```php +User::where('active', true)->get(); +Order::where('status', 'pending')->get(); +``` + +When a query builder operation should follow a model's configured table name, use `(new User)->getTable()`. For complex joins or raw SQL, explicit table names may be clearer; keep those references covered by tests when schema changes are possible. + +In migrations, use explicit table names rather than application models. Migrations are historical snapshots, while models and their scopes can change after a migration is deployed. diff --git a/.agents/skills/laravel-best-practices/rules/error-handling.md b/.agents/skills/laravel-best-practices/rules/error-handling.md new file mode 100644 index 0000000..afcdf4a --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/error-handling.md @@ -0,0 +1,77 @@ +# Error Handling Best Practices + +## Choose Where to Report and Render Exceptions + +Laravel supports exception-specific methods and centralized handler callbacks. Follow the pattern already established by the project. + +Exception methods keep behavior beside the exception definition: + +```php +class InvalidOrderException extends Exception +{ + public function report(): void + { + // Send the exception to a custom reporter. + } + + public function render(Request $request): Response + { + return response()->view('errors.invalid-order', status: 422); + } +} +``` + +Centralized callbacks in `bootstrap/app.php` keep the application's exception policy together: + +```php +->withExceptions(function (Exceptions $exceptions) { + $exceptions->report(function (InvalidOrderException $e) { + // Send the exception to a custom reporter. + }); + $exceptions->render(function (InvalidOrderException $e, Request $request) { + return response()->view('errors.invalid-order', status: 422); + }); +}) +``` + +An exception's `report()` method suppresses Laravel's default reporting unless it returns `false`. A report callback allows default reporting unless it returns `false` or is chained with `stop()`. Use `ShouldntReport` or `dontReport()` when the handler should not report an exception at all. By contrast, returning `false` from a `render()` method or render callback defers to Laravel's default rendering. + +## Mark Exceptions the Handler Should Not Report + +Implementing `ShouldntReport` prevents Laravel's exception handler from reporting that exception type and keeps the policy visible on the class. It does not prevent application code from logging the exception explicitly. + +```php +class PodcastProcessingException extends Exception implements ShouldntReport {} +``` + +## Throttle High-Volume Exception Reports + +A failing integration can flood logs or error tracking. Configure `throttle()` with a `Lottery` or `Limit` result to sample or rate-limit matching exception reports. Choose keys deliberately when separate exception classes, tenants, or integrations need independent limits. + +## Prevent Duplicate Reports of One Exception Instance + +Enable `dontReportDuplicates()` when the same exception object may pass through multiple `report($exception)` calls. It deduplicates by object identity, not by exception class or message. + +## Define JSON Rendering for API Routes + +Laravel normally uses request content negotiation to decide whether to render an exception as JSON. If the application's API contract requires JSON regardless of the `Accept` header, define that policy explicitly for the relevant routes. + +```php +$exceptions->shouldRenderJsonWhen(function (Request $request, Throwable $e) { + return $request->is('api/*') || $request->expectsJson(); +}); +``` + +## Add Context to Exception Classes + +Attach structured data to an exception through `context()`. Laravel merges that data into the exception's log context when the handler reports it. + +```php +class InvalidOrderException extends Exception +{ + public function context(): array + { + return ['order_id' => $this->orderId]; + } +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/events-notifications.md b/.agents/skills/laravel-best-practices/rules/events-notifications.md new file mode 100644 index 0000000..a8cce31 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/events-notifications.md @@ -0,0 +1,52 @@ +# Events and Notifications Best Practices + +## Rely on Event Discovery + +Laravel discovers listeners in the configured listener directories by inspecting type-hinted event arguments on `handle()` or `__invoke()` methods. Register listeners manually only when discovery is disabled, the listener is outside those directories, or explicit registration is clearer. + +## Cache Event Discovery During Production Deployment + +Cache discovered listeners during production deployment with `php artisan optimize` or `php artisan event:cache`. Rebuild the cache whenever listener definitions change. + +## Use `ShouldDispatchAfterCommit` Inside Transactions + +When an event is dispatched inside a database transaction, `ShouldDispatchAfterCommit` delays dispatch until all open database transactions commit. If a transaction rolls back, Laravel discards the event. This affects synchronous and queued listeners; it is not limited to queue timing. + +```php +class OrderShipped implements ShouldDispatchAfterCommit {} +``` + +## Queue Slow Notifications + +Queue notifications that call external services, such as email, text messaging, or Slack, when they do not need to complete before the response. Keep a notification synchronous when immediate completion or failure feedback is part of the operation. + +```php +class InvoicePaid extends Notification implements ShouldQueue +{ + use Queueable; +} +``` + +## Dispatch Queued Notifications After Commit + +A queued notification sent inside a database transaction can run before the transaction commits. Call `afterCommit()` on the queued notification, or enable the queue connection's `after_commit` option, when its delivery depends on committed data. This setting has no scheduling effect on a synchronous notification. + +```php +$user->notify((new InvoicePaid($invoice))->afterCommit()); +``` + +## Route Notification Channels to Dedicated Queues + +Different notification channels can have different latency and priority requirements. Implement `viaQueues()` when channels should use separate queues. + +## Use On-Demand Notifications for Non-User Recipients + +Avoid creating dummy models to send notifications to arbitrary addresses. + +```php +Notification::route('mail', 'admin@example.com')->notify(new SystemAlert()); +``` + +## Implement `HasLocalePreference` on Notifiable Models + +Implement `HasLocalePreference::preferredLocale()` on a notifiable model when notifications and mailables should use the recipient's locale. Laravel also preserves that locale for queued delivery. An explicit `locale()` call can still override the preference for an individual notification. diff --git a/.agents/skills/laravel-best-practices/rules/http-client.md b/.agents/skills/laravel-best-practices/rules/http-client.md new file mode 100644 index 0000000..cc8fdd6 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/http-client.md @@ -0,0 +1,157 @@ +# HTTP Client Best Practices + +## Set Explicit Timeouts + +Laravel's HTTP client has a 30-second response timeout by default. Choose response and connection timeouts that fit the service and the calling request or job. Remember that retries can multiply the total elapsed time. + +Less resilient: + +```php +$response = Http::get('https://api.example.com/users'); +``` + +Preferred: + +```php +$response = Http::connectTimeout(3) + ->timeout(5) + ->get('https://api.example.com/users'); +``` + +Define shared settings in a macro or a dedicated client: + +```php +Http::macro('github', function () { + return Http::baseUrl('https://api.github.com') + ->connectTimeout(3) + ->timeout(10) + ->withToken(config('services.github.token')); +}); + +$response = Http::github()->get('/repos/laravel/framework'); +``` + +## Retry Only Safe Operations + +Retry transient connection failures, rate-limit responses, and server errors with an appropriate delay. Retry idempotent requests such as `GET` when the operation can safely run more than once. Retry a state-changing request only when the remote API supports an idempotency key or provides equivalent duplicate protection. + +Unsafe without an idempotency guarantee: + +```php +$response = Http::retry([100, 500, 1000]) + ->post('https://api.example.com/v1/charges', $data); +``` + +Safe for an idempotent request: + +```php +$response = Http::connectTimeout(3) + ->timeout(10) + ->retry([100, 500, 1000], 0, function (Throwable $exception) { + return $exception instanceof ConnectionException + || ($exception instanceof RequestException + && ($exception->response->serverError() || $exception->response->status() === 429)); + }) + ->get('https://api.example.com/data'); +``` + +For a supported state-changing API, send a stable idempotency key for every attempt: + +```php +$response = Http::withHeaders(['Idempotency-Key' => $paymentAttempt->uuid]) + ->connectTimeout(3) + ->timeout(10) + ->retry([100, 500, 1000], 0, function (Throwable $exception) { + return $exception instanceof ConnectionException + || ($exception instanceof RequestException + && ($exception->response->serverError() || $exception->response->status() === 429)); + }) + ->post('https://api.example.com/v1/charges', $data); +``` + +## Handle Errors Explicitly + +The HTTP client returns responses for `4xx` and `5xx` status codes instead of throwing by default. Inspect the expected statuses or call `throw()` before consuming a success payload. + +Unsafe when a success payload is expected: + +```php +$user = Http::get('https://api.example.com/users/1')->json(); +``` + +Preferred: + +```php +$user = Http::connectTimeout(3) + ->timeout(5) + ->get('https://api.example.com/users/1') + ->throw() + ->json(); +``` + +Handle expected alternatives explicitly when graceful degradation is required: + +```php +$response = Http::connectTimeout(3) + ->timeout(5) + ->get('https://api.example.com/users/1'); + +if ($response->successful()) { + return $response->json(); +} + +if ($response->notFound()) { + return null; +} + +$response->throw(); +``` + +## Pool Independent Requests + +Use `Http::pool()` when several independent requests can run concurrently. Pooling changes execution time, not error handling; inspect or throw for each response as needed. + +```php +use Illuminate\Http\Client\Pool; + +$responses = Http::pool(fn (Pool $pool) => [ + $pool->as('users')->connectTimeout(3)->timeout(5) + ->get('https://api.example.com/users'), + $pool->as('posts')->connectTimeout(3)->timeout(5) + ->get('https://api.example.com/posts'), +]); + +$users = $responses['users']->throw()->json(); +$posts = $responses['posts']->throw()->json(); +``` + +## Fake HTTP Requests in Tests + +Use `Http::fake()` for external integrations, and use `Http::preventStrayRequests()` when an unexpected real request should fail the test. Also test timeouts, connection failures, and error responses that the application handles. + +```php +it('syncs a user from the API', function () { + Http::preventStrayRequests(); + + Http::fake([ + 'api.example.com/users/1' => Http::response([ + 'name' => 'John Doe', + 'email' => 'john@example.com', + ]), + ]); + + (new UserSyncService)->sync(1); + + Http::assertSent(fn (Request $request) => + $request->url() === 'https://api.example.com/users/1' + ); +}); +``` + +For example, fake a connection failure when testing the integration's failure path: + +```php +Http::fake([ + 'api.example.com/*' => Http::failedConnection(), +]); +``` diff --git a/.agents/skills/laravel-best-practices/rules/mail.md b/.agents/skills/laravel-best-practices/rules/mail.md new file mode 100644 index 0000000..f631043 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/mail.md @@ -0,0 +1,54 @@ +# Mail Best Practices + +## Queue Slow Mail Delivery + +Implement `ShouldQueue` on a mailable when delivery should normally happen in the background. Laravel queues that mailable even when the call site uses `Mail::send()`. + +```php +class OrderShipped extends Mailable implements ShouldQueue +{ + use Queueable, SerializesModels; +} +``` + +Keep mail synchronous when the caller must know immediately whether delivery was accepted, or when no queue worker is available. + +## Dispatch Queued Mail After Commit + +A queued mailable dispatched during a database transaction can be processed before the transaction commits. Call `afterCommit()` on the mailable, or enable the queue connection's `after_commit` option, when the mail depends on committed records. + +```php +Mail::to($user)->send( + (new OrderShipped($order))->afterCommit() +); +``` + +If the transaction rolls back, an after-commit mailable is not dispatched. This setting affects queued mail only; it does not defer synchronous delivery. + +## Assert the Delivery Mode + +Use `Mail::assertQueued()` for queued mailables and `Mail::assertSent()` for synchronously sent mailables. + +Incorrect for a mailable that implements `ShouldQueue`: + +```php +Mail::assertSent(OrderShipped::class); +``` + +Correct: + +```php +Mail::assertQueued(OrderShipped::class); +``` + +## Use Markdown Mailables When They Fit + +Markdown mailables render HTML and plain-text versions from Laravel's mail components and support publishable themes. They are useful for conventional transactional messages, but a custom HTML and text pair may be more appropriate for a specialized design. + +```bash +php artisan make:mail OrderShipped --markdown=mail.orders.shipped +``` + +## Separate Content and Delivery Tests + +Test rendered content by instantiating the mailable and using assertions such as `assertSeeInHtml()` and `assertSeeInText()`. Test delivery separately with `Mail::fake()` and `assertSent()` or `assertQueued()` so failures identify the affected behavior. diff --git a/.agents/skills/laravel-best-practices/rules/migrations.md b/.agents/skills/laravel-best-practices/rules/migrations.md new file mode 100644 index 0000000..3345402 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/migrations.md @@ -0,0 +1,67 @@ +# Migration Best Practices + +## Generate Migrations with Artisan + +Use `php artisan make:migration` to generate the timestamped filename and migration structure. + +```bash +php artisan make:migration create_posts_table +php artisan make:migration add_slug_to_posts_table +``` + +## Define Foreign-Key Constraints Deliberately + +Use `constrained()` when its naming conventions and default actions match the relationship. Specify the table or delete behavior when they do not. + +```php +$table->foreignId('user_id')->constrained()->cascadeOnDelete(); +$table->foreignId('author_id')->constrained('users'); +``` + +Do not add a duplicate single-column index without checking the database driver's treatment of foreign-key indexes and the indexes already created by the migration. + +## Treat Deployed Migrations as Immutable + +After a migration has run in a shared or production environment, create a new migration for subsequent changes. Editing the old file makes fresh installations differ from upgraded installations. + +For a local migration that has not been shared or deployed, editing and rerunning it may be simpler. + +## Design Indexes for Real Queries + +Add indexes based on query patterns, selectivity, write cost, and the database's ability to use composite indexes. A column appearing in `WHERE`, `ORDER BY`, or `JOIN` does not automatically need its own index. + +Declare each selected index in the schema migration that creates or changes the relevant table. Confirm important indexes with representative data and the database's query plan, and avoid redundant indexes whose leading columns duplicate an existing index without serving a distinct query. See the database performance and advanced query rules for index selection and column-order guidance. + +## Stage Changes That Affect Existing Rows + +Adding a required or unique column to a populated table often needs multiple deployment-safe steps. Add a nullable column, deploy code that can handle both states, backfill existing rows in bounded chunks, then add the required constraint or index after the data is valid. + +Do not assume this migration is safe on a populated table: + +```php +$table->string('slug')->unique(); +``` + +Large backfills are usually better implemented as an observable, restartable command or job than inside a schema migration. Small deterministic data changes may be reasonable in a migration when their locking, transaction, and deployment behavior is understood. + +## Mirror Defaults Only When Unsaved Models Need Them + +A database default is applied when a row is inserted, not when a model is instantiated. Mirror the value in the model's `$attributes` only when application code must observe that default before persistence, and keep both definitions synchronized. + +```php +// Migration +$table->string('status')->default('pending'); + +// Model +protected $attributes = [ + 'status' => 'pending', +]; +``` + +## Make Rollbacks Honest + +Implement `down()` when the change can be safely reversed. A rollback that drops populated columns or cannot restore transformed data is destructive even if it is syntactically reversible; document that limitation and prefer a forward-fix migration in production. + +## Keep Migrations Focused + +Keep each migration small enough to reason about, deploy, and reverse. Separate long-running backfills from schema changes when doing so reduces locks and supports phased deployment, but do not split related operations merely to enforce a blanket separation between data definition and data manipulation. diff --git a/.agents/skills/laravel-best-practices/rules/queue-jobs.md b/.agents/skills/laravel-best-practices/rules/queue-jobs.md new file mode 100644 index 0000000..011828a --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/queue-jobs.md @@ -0,0 +1,117 @@ +# Queue and Job Best Practices + +## Keep Reservation Time Longer Than Execution Time + +For queue drivers that use Laravel's `retry_after` setting, configure it to exceed the longest worker or job timeout by a safety margin. When a reservation expires, another worker can reserve the same job while the first process is still running. Keep the worker's `--timeout` several seconds shorter than `retry_after`. + +```php +// Job +public $timeout = 120; + +// config/queue.php for the connection +'retry_after' => 150, +``` + +Amazon Simple Queue Service uses its visibility timeout instead of Laravel's `retry_after`; configure that timeout at the queue level. Because workers can also stop after side effects but before acknowledging a job, make important jobs idempotent even with correct timeout settings. + +## Back Off Transient Failures + +Use progressively longer delays when a dependency needs time to recover. Do not retry permanent validation or business-rule failures. + +```php +class SyncWithStripe implements ShouldQueue +{ + public $tries = 4; + + public $backoff = [1, 5, 10]; +} +``` + +Rate-limiting and exception-throttling middleware can release jobs back to the queue. Released attempts may still count toward the maximum attempt limit, so configure `$tries` or `retryUntil()` to allow the intended retry window. + +## Use Unique Jobs for Dispatch Deduplication + +Implement `ShouldBeUnique` when only one queued instance of a logical job should exist. Uniqueness uses a cache lock and is not a substitute for idempotent processing or a database constraint. + +```php +class GenerateInvoice implements ShouldQueue, ShouldBeUnique +{ + public $uniqueFor = 3600; + + public function uniqueId(): string + { + return (string) $this->order->id; + } +} +``` + +All dispatching processes must use a shared cache that supports locks. Unique-job constraints do not apply to jobs within batches. + +Use `ShouldBeUniqueUntilProcessing` only when the lock should be released immediately before processing begins, allowing another instance to be dispatched while the first is running: + +```php +class UpdateSearchIndex implements ShouldQueue, ShouldBeUniqueUntilProcessing +{ + // ... +} +``` + +## Handle Terminal Failure When Needed + +Implement `failed()` when the application must update state, alert an operator, or record domain-specific context after all attempts are exhausted. Logging every failure in each job may duplicate the queue system's failure reporting. + +Laravel invokes `failed()` on a new job instance, so mutations made to the job during `handle()` are not available there. + +```php +public function failed(?Throwable $exception): void +{ + $this->podcast->update(['status' => 'failed']); + + Log::error('Podcast processing failed', [ + 'podcast_id' => $this->podcast->id, + 'exception' => $exception, + ]); +} +``` + +## Rate Limit External Calls + +Use queue middleware such as `RateLimited` when jobs share a third-party API quota. Define the named limiter and choose release delays and attempt limits together. + +```php +public function middleware(): array +{ + return [new RateLimited('external-api')]; +} +``` + +## Batch Jobs for Group Coordination + +Use `Bus::batch()` to monitor a group of jobs and run callbacks when the batch completes or encounters failures. A batch is not a database transaction: completed jobs are not rolled back when another job fails. By default, one failed job cancels the batch; call `allowFailures()` only when partial failure is acceptable. + +```php +Bus::batch([ + new ImportCsvChunk($chunk1), + new ImportCsvChunk($chunk2), +]) + ->then(fn (Batch $batch) => Notification::send($user, new ImportComplete)) + ->catch(fn (Batch $batch, Throwable $exception) => Log::error('Import batch failed', [ + 'exception' => $exception, + ])) + ->dispatch(); +``` + +## Configure Time-Based Retry Limits Deliberately + +Use `retryUntil()` as the time-based alternative to a maximum attempt count. Laravel may attempt the job any number of times until this deadline, subject to other failure conditions such as maximum exceptions. The method takes precedence over attempt-based limits, so setting `$tries = 0` is not required. + +```php +public function retryUntil(): DateTimeInterface +{ + return now()->addHours(4); +} +``` + +## Use Horizon for Redis Queue Operations + +Laravel Horizon provides monitoring, balancing, metrics, and supervisor configuration for Redis queues. It does not support non-Redis queue drivers. diff --git a/.agents/skills/laravel-best-practices/rules/routing.md b/.agents/skills/laravel-best-practices/rules/routing.md new file mode 100644 index 0000000..604a8d9 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/routing.md @@ -0,0 +1,106 @@ +# Routing and Controller Best Practices + +## Use Implicit Route Model Binding + +Let Laravel resolve models from route parameters when the default lookup and missing-model behavior fit the endpoint. + +Instead of manual lookup: + +```php +public function show(int $id): View +{ + $post = Post::findOrFail($id); + + return view('posts.show', ['post' => $post]); +} +``` + +Use route model binding: + +```php +public function show(Post $post): View +{ + return view('posts.show', ['post' => $post]); +} +``` + +## Scope Nested Bindings + +Use scoped bindings when a nested resource must belong to its parent. This constrains model resolution; it does not replace authorization. + +```php +Route::get('/users/{user}/posts/{post}', function (User $user, Post $post) { + // The resolved post belongs to the resolved user. +})->scopeBindings(); +``` + +## Use Resource Routes for Resourceful Actions + +Use `Route::resource()` or `Route::apiResource()` when the endpoint follows Laravel's resource-controller actions. Define explicit routes when the behavior does not fit that vocabulary. + +```php +Route::resource('posts', PostController::class); + +// Alternatively, for an API-only resource: +Route::apiResource('posts', ApiPostController::class); +``` + +`apiResource()` omits the HTML-oriented `create` and `edit` routes. It does not itself add an `/api` prefix; that prefix comes from the application's API route configuration. + +## Organize Controllers Around Resources + +As a general default, organize each controller around one resource and use Laravel's standard resource actions: `index`, `show`, `create`, `store`, `edit`, `update`, and `destroy`. This keeps routes predictable and prevents controllers from accumulating unrelated behavior. + +When a controller needs a custom action such as `publish`, `approve`, or `archive`, first consider whether that behavior represents a separate resource. A focused resource controller gives the behavior its own authorization, validation, and middleware boundary. + +Custom action on the primary controller: + +```php +Route::post('/podcasts/{podcast}/publish', [PodcastController::class, 'publish']); +``` + +The published podcast modeled as a resource: + +```php +Route::post('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'store']) + ->name('published-podcasts.store'); + +Route::delete('/published-podcasts/{podcast}', [PublishedPodcastController::class, 'destroy']) + ->name('published-podcasts.destroy'); +``` + +```php +class PublishedPodcastController extends Controller +{ + public function store(Podcast $podcast): RedirectResponse + { + $podcast->publish(); + + return back(); + } + + public function destroy(Podcast $podcast): RedirectResponse + { + $podcast->unpublish(); + + return back(); + } +} +``` + +Treat a custom verb as a design signal, not proof that another controller is required. Use query parameters for simple filtering, and keep an explicit action route when modeling the operation as a resource would obscure the domain or conflict with established project conventions. + +## Keep Controllers Focused on HTTP Concerns + +Controllers should coordinate HTTP input, authorization, validation, an application operation, and the response. Extract substantial or reusable business logic, but do not introduce an action or service merely to satisfy an arbitrary line limit. + +```php +public function store(StorePostRequest $request, CreatePostAction $create): RedirectResponse +{ + $post = $create->handle($request->validated()); + + return redirect()->route('posts.show', $post); +} +``` + +A form request can perform validation and authorization before the controller runs. Do not repeat its rules in the controller. Keep simple, endpoint-specific validation inline when extraction would not improve reuse or clarity; see the validation rules for detailed guidance. diff --git a/.agents/skills/laravel-best-practices/rules/scheduling.md b/.agents/skills/laravel-best-practices/rules/scheduling.md new file mode 100644 index 0000000..4c25134 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/scheduling.md @@ -0,0 +1,61 @@ +# Task Scheduling Best Practices + +## Prevent Unwanted Overlap + +Use `withoutOverlapping()` when a second run must not begin while the previous run holds the lock. This is appropriate for variable-duration tasks that are not safe to run concurrently. + +```php +Schedule::command('reports:generate') + ->everyFifteenMinutes() + ->withoutOverlapping(30); +``` + +The optional value is the lock expiration time in minutes, not the task timeout. Choose it carefully: the default is 24 hours, stale locks can be cleared with `php artisan schedule:clear-cache`, and an expiration that is too short can permit overlap while the first task still runs. The task itself should still tolerate retries and partial execution where practical. + +## Run a Task on One Server + +Use `onOneServer()` when only one scheduler node should run an eligible task. Scheduler nodes must use the same default cache store, and that store must support atomic locks. Supported stores include `database`, `memcached`, `dynamodb`, and `redis`. + +```php +Schedule::command('billing:charge')->daily()->onOneServer(); +``` + +Name scheduled closures before applying `onOneServer()`, especially when scheduling the same closure with different parameters, so each task has a distinct lock identity. + +## Run Eligible Commands in the Background + +Tasks due at the same time run sequentially by default. Use `runInBackground()` when an independent, long-running scheduled command should not delay later tasks. + +```php +Schedule::command('analytics:process')->hourly()->runInBackground(); +``` + +Laravel restricts `runInBackground()` to tasks scheduled with `command()` and `exec()`; it is not available for scheduled closures. Ensure background processes have appropriate logging and failure monitoring. + +## Restrict Tasks by Environment + +Use `environments()` when a task should run only in named application environments. Treat this as an operational safeguard, not an authorization control. + +```php +Schedule::command('billing:charge') + ->monthly() + ->environments(['production']); +``` + +## Group Shared Configuration + +Use schedule groups when several tasks genuinely share frequency or constraints. + +```php +Schedule::daily() + ->onOneServer() + ->timezone('America/New_York') + ->group(function () { + Schedule::command('emails:send --force'); + Schedule::command('emails:prune'); + }); +``` + +## Bound Work Inside the Task + +The scheduler does not provide a `takeUntilTimeout()` event method or terminate arbitrary tasks at a deadline. Bound work in the command or job itself by processing finite chunks, checking a deadline, or dispatching queue jobs with suitable timeouts. Use operating-system or process controls when hard termination is required. diff --git a/.agents/skills/laravel-best-practices/rules/security.md b/.agents/skills/laravel-best-practices/rules/security.md new file mode 100644 index 0000000..57b57f0 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/security.md @@ -0,0 +1,156 @@ +# Security Best Practices + +## Control Mass Assignment + +Define `$fillable` when a model is populated from request-derived arrays, or deliberately guard attributes by another consistent model convention. Laravel models guard all attributes by default; `$guarded = []` opts out of that protection. + +```php +class User extends Model +{ + protected $fillable = [ + 'name', + 'email', + 'password', + ]; +} +``` + +Do not pass untrusted request data to a model with `$guarded = []`. Mass-assignment protection controls which attributes `create()`, `fill()`, and `update()` may set; it does not validate values or authorize the operation. + +## Authorize Protected Actions + +Use policies, gates, or form request authorization for actions that depend on the current user's permissions. Authentication alone does not establish permission, and validation is not authorization. + +```php +public function update(UpdatePostRequest $request, Post $post): RedirectResponse +{ + Gate::authorize('update', $post); + + $post->update($request->validated()); + + return redirect()->route('posts.show', $post); +} +``` + +Authorization may instead live in the form request: + +```php +public function authorize(): bool +{ + return $this->user()?->can('update', $this->route('post')) ?? false; +} +``` + +Public actions intentionally available to everyone do not need a redundant authorization check. + +## Bind Query Parameters + +Use Eloquent, the query builder, or explicit bindings instead of interpolating untrusted values into Structured Query Language (SQL). Bindings protect values, not identifiers such as column names or sort directions; map user-selected identifiers to an allow-list. + +Incorrect: + +```php +DB::select("SELECT * FROM users WHERE name = '{$request->name}'"); +``` + +Correct: + +```php +User::where('name', $request->name)->get(); +User::whereRaw('LOWER(name) = ?', [$request->string('name')->lower()->toString()])->get(); +``` + +## Escape Output in Its Context + +Blade's `{{ }}` syntax HTML-escapes output. Use `{!! !!}` only for content that has been sanitized for the exact HTML context in which it is rendered. Escaping rules differ for HTML, URLs, JavaScript, and Cascading Style Sheets. + +Incorrect for untrusted content: + +```blade +{!! $user->bio !!} +``` + +Correct: + +```blade +{{ $user->bio }} +``` + +## Apply Cross-Site Request Forgery Protection + +Include `@csrf` in state-changing Blade forms handled by Laravel's `web` middleware. Routes intentionally excluded from cross-site request forgery (CSRF) verification, such as validated third-party webhooks, need their own authenticity check. + +```blade +
+ @csrf + +
+``` + +Inertia applications commonly use Axios, which returns the encrypted `XSRF-TOKEN` cookie in the `X-XSRF-TOKEN` header. Confirm equivalent configuration when using another HTTP client. Do not disable CSRF protection merely to fix a token mismatch. + +## Rate Limit Sensitive Endpoints + +Apply suitable rate limits to login attempts, password recovery, verification messages, and expensive or abuse-prone application programming interface (API) routes. Choose the limiter key deliberately; an Internet Protocol (IP) address alone can unfairly group users behind a shared network, while an account identifier alone can enable targeted denial of service. + +```php +RateLimiter::for('login', function (Request $request) { + return Limit::perMinute(5)->by(Str::transliterate( + Str::lower($request->string('email')).'|'.$request->ip() + )); +}); + +Route::post('/login', LoginController::class)->middleware('throttle:login'); +``` + +Rate limiting reduces abuse; it does not replace authentication, authorization, or upstream denial-of-service protection. + +## Validate and Store Uploads Safely + +Validate expected content type, dimensions where relevant, and size. Laravel's `mimes` rule reads the file contents and guesses a Multipurpose Internet Mail Extensions (MIME) type corresponding to the listed extensions; it does not validate the user-assigned filename extension. The `extensions` rule checks that extension and should not be used by itself. + +```php +public function rules(): array +{ + return [ + 'avatar' => ['required', 'image', 'mimes:jpg,jpeg,png,webp', 'max:2048'], + ]; +} +``` + +Use Laravel's storage methods to generate a filename, and store untrusted files outside a publicly executable location. Public files can require additional controls, such as image re-encoding, content-disposition headers, and explicit blocking of active formats. + +```php +$path = $request->file('avatar')->store('avatars'); +``` + +## Keep Secrets Out of Application Code + +Do not commit populated environment files or hard-code credentials. Read environment variables in configuration files, then use `config()` in application code so configuration caching works correctly. See the configuration rules for encrypted environment files and external secret stores. + +## Audit Dependencies + +Run `composer audit` regularly and in continuous integration. Review findings for exploitability and update or mitigate affected packages promptly. + +```bash +composer audit +``` + +## Encrypt Sensitive Attributes When Appropriate + +Use an `encrypted` cast for sensitive values that must be recoverable, and use `$hidden` to omit them from array and JavaScript Object Notation (JSON) serialization. Hidden attributes remain accessible in PHP, and encryption does not replace access control. Encrypted values cannot be meaningfully queried and should use a `TEXT` or larger column because ciphertext length is variable. + +```php +class Integration extends Model +{ + protected $hidden = ['api_key', 'api_secret']; + + protected function casts(): array + { + return [ + 'api_key' => 'encrypted', + 'api_secret' => 'encrypted', + ]; + } +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/style.md b/.agents/skills/laravel-best-practices/rules/style.md new file mode 100644 index 0000000..3f3f14f --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/style.md @@ -0,0 +1,110 @@ +# Convention and Style Best Practices + +## Follow Project Naming Conventions + +Prefer Laravel's conventions in new code, but preserve an established project convention unless a coordinated rename is worthwhile. + +| Element | Convention | Example | +| --- | --- | --- | +| Controller | Singular resource name | `ArticleController` | +| Model | Singular StudlyCase | `User` | +| Table | Plural snake_case | `article_comments` | +| Pivot table | Singular model names in alphabetical order, in snake_case | `article_user` | +| Column | snake_case | `meta_title` | +| Conventional foreign key | Singular model name plus `_id`, in snake_case | `article_id` | +| Resource URI | Plural resource | `articles/1` | +| Route name | Dotted segments; snake_case within a segment when needed | `users.show_active` | +| Method | camelCase | `getAll` | +| Variable | camelCase | `$articlesWithAuthor` | +| Collection | Descriptive and plural | `$activeUsers` | +| Object | Descriptive and singular | `$activeUser` | +| View | kebab-case | `show-filtered.blade.php` | +| Configuration file | snake_case | `google_calendar.php` | +| Enumeration | Singular StudlyCase | `UserType` | + +## Prefer Clear, Idiomatic Syntax + +Use Laravel helpers and query methods when they communicate intent more directly. Do not shorten code when the result is ambiguous or loses useful type information. + +| More verbose | Idiomatic alternative | +| --- | --- | +| `Session::get('cart')` | `session('cart')` | +| `$request->session()->get('cart')` | `session('cart')` | +| `return Redirect::back()` | `return back()` | +| `Carbon::now()` | `now()` | +| `->where('column', '=', 1)` | `->where('column', 1)` | +| `->orderBy('created_at', 'desc')` | `->latest()` | +| `->orderBy('created_at', 'asc')` | `->oldest()` | +| `->first()?->name` | `->value('name')` when only that value is needed | + +Use typed request accessors such as `$request->string()`, `$request->integer()`, and `$request->boolean()` when their coercion matches the operation. + +## Use Utilities When They Clarify Intent + +Laravel's `Str`, `Arr`, `Number`, and `Uri` utilities provide expressive operations and framework-consistent behavior. Prefer them when they are clearer or safer than an equivalent PHP operation, not as an unconditional replacement for every built-in function. + +```php +$slug = Str::slug($title); +$short = Str::limit($text, 100); +$class = class_basename(User::class); +$result = Str::of($input)->trim()->replace('_', '-')->lower(); +``` + +Use `Arr` for dot notation and common transformations: + +```php +$name = Arr::get($array, 'user.name', 'default'); +$public = Arr::only($attributes, ['name', 'email']); +``` + +Use `Number` for localized display formatting rather than values that will be stored or calculated: + +```php +Number::format(1000000); +Number::currency(1500, 'USD'); +Number::fileSize(1024 * 1024); +``` + +Use `Uri` when constructing or transforming a uniform resource identifier (URI) benefits from a structured API: + +```php +$uri = Uri::of('https://example.com/search') + ->withQuery(['q' => 'laravel', 'page' => 1]); +``` + +Check the documentation for the Laravel version supported by the project before using newer utility classes or methods. + +## Keep Presentation Code Maintainable + +Prefer the project's asset pipeline, components, and existing conventions for substantial JavaScript and Cascading Style Sheets (CSS). Small page-specific scripts or styles can be reasonable in Blade layouts or stacks; avoid mixing large behavior and style blocks into templates. + +Pass server data with an encoding mechanism appropriate to its context. For example, Blade's `Js::from()` safely formats data for JavaScript: + +```blade + +``` + +Data attributes are useful for small scalar values, but serializing a large model into an attribute can expose unnecessary fields and complicate escaping. + +## Write Comments That Explain Why + +Prefer clear names and small units of code over comments that merely restate an operation. Add concise comments for non-obvious constraints, tradeoffs, workarounds, regular expressions, or external behavior that the code cannot express by itself. Keep comments accurate when behavior changes. + +Unhelpful: + +```php +// Check whether the query has joins. +if (count((array) $builder->getQuery()->joins) > 0) { + // ... +} +``` + +Clearer: + +```php +if ($this->hasJoins()) { + // ... +} +``` diff --git a/.agents/skills/laravel-best-practices/rules/validation.md b/.agents/skills/laravel-best-practices/rules/validation.md new file mode 100644 index 0000000..37ce6c5 --- /dev/null +++ b/.agents/skills/laravel-best-practices/rules/validation.md @@ -0,0 +1,89 @@ +# Validation and Forms Best Practices + +## Extract Validation When It Improves the Boundary + +Use a form request when validation or authorization is substantial, reused, or clearer outside the controller. Inline `$request->validate()` remains appropriate for a small, endpoint-specific rule set. + +```php +public function store(StorePostRequest $request): RedirectResponse +{ + $post = Post::create($request->validated()); + + return redirect()->route('posts.show', $post); +} +``` + +A form request's `authorize()` method can enforce access to the operation. Validation establishes the shape and values of input; it does not itself authorize the user. + +## Prefer Readable Rule Syntax + +Array syntax composes cleanly with rule objects and avoids delimiter issues. Prefer it in new code when it improves readability, while following a consistent local style. + +```php +'email' => ['required', 'email', Rule::unique('users')], +``` + +String syntax remains valid for simple rules: + +```php +'email' => 'required|email|unique:users', +``` + +## Use Only Intended Validated Data + +Use `validated()` or `safe()` instead of `$request->all()` when passing request data onward. Then select the fields intended for the operation when the validation rules also cover control fields or nested data. + +Unsafe: + +```php +Post::create($request->all()); +``` + +Preferred: + +```php +$post = Post::create($request->safe()->only(['title', 'body'])); +``` + +Validated data is not automatically safe for mass assignment. Keep model `$fillable` or `$guarded` rules aligned with the operation, and never add a sensitive attribute to validation merely to make mass assignment convenient. + +## Express Conditional Rules Clearly + +Use conditional rules such as `Rule::when()`, `required_if`, or `exclude_unless` when they make the condition explicit. Choose the simplest form that remains easy to test. + +```php +'company_name' => [ + 'string', + 'max:255', + Rule::when( + $this->input('account_type') === 'business', + ['required'], + ['nullable'], + ), +], +``` + +## Add Cross-Field Validation After Base Rules + +Use a form request's `after()` method for validation that depends on multiple fields or application state. Avoid expensive queries when prerequisite fields have already failed validation. + +```php +public function after(): array +{ + return [ + function (Validator $validator) { + if ($validator->errors()->hasAny(['product_id', 'quantity'])) { + return; + } + + $stock = Product::find($this->integer('product_id'))?->stock; + + if ($stock !== null && $this->integer('quantity') > $stock) { + $validator->errors()->add('quantity', 'Not enough stock.'); + } + }, + ]; +} +``` + +Validation against mutable state does not prevent a race between validation and persistence. Enforce inventory, uniqueness, and similar invariants with database constraints, atomic updates, or a database transaction as appropriate. diff --git a/.agents/skills/nativephp-agent-loop/SKILL.md b/.agents/skills/nativephp-agent-loop/SKILL.md new file mode 100644 index 0000000..45f2a97 --- /dev/null +++ b/.agents/skills/nativephp-agent-loop/SKILL.md @@ -0,0 +1,109 @@ +--- +name: nativephp-agent-loop +description: "Autonomous build-verify loop for NativePHP Mobile. Activate when the user asks you to build, run, launch, verify, screenshot, or iterate on a NativePHP mobile app on a simulator or emulator — and drive the loop yourself instead of telling the user to run commands. Uses the headless --json artisan commands (native:run, native:status, native:screenshot, native:tail, native:open-url, native:devices) to build, launch, observe and re-verify." +--- + +# NativePHP Mobile — Agent Build/Verify Loop + +Drive the device cycle yourself: edit code → build → launch on a simulator/emulator → look at the +screen → fix → re-verify. Everything here uses the headless `--json` command surface in core. + +## When this applies + +Activate when the user asks you to **build, run, verify, or iterate** on the app (not merely to write code) +and the target is a **simulator/emulator with a debug build**. Otherwise follow `nativephp-mobile`'s +"Build Commands — Run Them Yourself" and "Building and Running" sections. + +**Always ask the user first** before: physical devices, release/bundle builds, `native:install`, uninstalling +apps, or `simctl shutdown`/`erase`. + +## Starting from zero (no app yet) + +```bash +composer create-project nativephp/mobile-starter --no-interaction +cd +# The starter pre-fills NATIVEPHP_APP_ID (unique) and version envs in .env. +# Add NATIVEPHP_DEEPLINK_SCHEME= so native:open-url can drive navigation. +php artisan native:install --force --no-interaction # runtime + nativephp/{ios,android} +``` + +Then the first `native:run --build=debug --no-tty --json` is the baseline build. + +## Preconditions & claiming a device + +1. `php artisan native:devices --json` — list simulators/emulators. Prefer one that is already `booted`. +2. Record your target so every later command is unambiguous (and other agents don't collide): + write `nativephp/agent-device.json` = `{"platform":"ios","udid":""}`. Every `--json` command + resolves this automatically; you can also pass `--device=` explicitly. +3. If nothing is booted: iOS `xcrun simctl boot ` (pick the newest iPhone); Android + `php artisan native:emulator android`, then re-run `native:devices`. +4. For `native:open-url`, set `NATIVEPHP_DEEPLINK_SCHEME=` in `.env` (a rebuild bakes it in). + +## The loop + +``` +edit code +└─ php artisan native:run --build=debug --no-tty --json (allow 10 min for first build) + ├─ ok:false, stage:build|install → read .logTail (or native:tail); fix; rebuild + ├─ ok:false, stage:verify → app built but isn't running: boot fatal. + │ laravel.log is usually EMPTY here (Laravel never got up). + │ native:tail --fatals --json; fix; rebuild + └─ ok:true + └─ php artisan native:screenshot --json → Read the PNG → judge against the goal + └─ exercise: php artisan native:open-url "://" --json → screenshot each screen + └─ all screens verified, nothing in the log → done. Report with the screenshot paths. +``` + +`native:run --json` emits one JSON object on the last stdout line. On success: +`{"ok":true,"platform":...,"device":...,"appId":...,"buildType":"debug","pid":...,"buildLog":...,"durationMs":...}`. +On failure it carries `stage` (`validate|devices|build|install|launch|verify`), `error`, and — for build/install +— a `logTail`. Exit code is 0 only when `ok:true`. + +### "Did it boot?" — the definition + +Treat the app as booted-OK when: `native:run --json` returned `ok:true` **and** `native:status --json` +shows `running:true` a few seconds later **and** the screenshot is not the red "Something went wrong" +error screen. + +## Reading exceptions + +Exceptions that reach Laravel go through its normal reporting, so `laravel.log` on the device is the +first stop: + +```bash +php artisan native:tail --lines=100 --json # the app's laravel.log, off the device +``` + +That covers anything thrown while the app is running — including native (EDGE) screens, which report +through Laravel like the rest of the app. + +**It does not cover boot fatals.** An app that dies before Laravel is up writes nothing to `laravel.log`. +The runtime records those on the device instead, along with true PHP fatals and uncaught throwables: + +```bash +php artisan native:tail --fatals --json # {"ok":true,"events":[{"kind":"boot_fatal","exception":{...}}]} +``` + +Each event's `exception.app_frame` is the first line in the app's own code, which is usually the one to fix. +An empty `events` list means nothing has crashed. Do not read a clean `laravel.log` as evidence the app +booted: when `native:run --json` returns `ok:false, stage:verify`, check `--fatals` and the screenshot. + +Anything richer (timelines, component state, screen trees, interactive inspection) comes from a devtools +package rather than core; follow that package's own skill if the project has one. + +## Exercising the app + +- `php artisan native:open-url "://" --json` for navigation. Note iOS simulators show a + one-time "Open in ?" confirmation for custom schemes. +- Raw `adb` (`input tap/text/keyevent`, `uiautomator dump`) for Android. +- `xcrun simctl` for iOS simulator lifecycle. + +Screenshot after every interaction and judge against the goal. + +## Hygiene + +- Never use `--watch` for discrete build-loop iterations (it blocks). +- Never edit generated files under `nativephp/ios` or `nativephp/android`. +- One rebuild at a time per app repo; don't run two agents against the same repo. +- Remove any throwaway/debug code you added before reporting done. +- Never `simctl shutdown`/`erase` a simulator unless the user asked — other agents may share it. diff --git a/.agents/skills/nativephp-mobile-ui/SKILL.md b/.agents/skills/nativephp-mobile-ui/SKILL.md new file mode 100644 index 0000000..e1c82bd --- /dev/null +++ b/.agents/skills/nativephp-mobile-ui/SKILL.md @@ -0,0 +1,117 @@ +--- +name: nativephp-mobile-ui +description: "Element reference for nativephp/mobile-ui, the plugin that renders every NativePHP EDGE element. Activate when writing or changing a NativePHP screen's Blade view: layout (column, row, stack, scroll-view), text, button, the text inputs (outlined-text-input, filled-text-input, bare-text-input), list and list-item (leading/trailing slots, swipe actions, trailing icon buttons), icon, top-bar, toggle, checkbox, select, and their events and native:model binding." +--- + +# nativephp/mobile-ui elements + +Every `` tag is drawn by this plugin, as SwiftUI on iOS and Jetpack Compose on Android. The plugin must be +registered in `plugins()` in `app/Providers/NativeServiceProvider.php` (`php artisan native:plugin:register +nativephp/mobile-ui`). The `native:` prefix is optional (`` works), but use it. + +## Events + +`@press` (alias `@tap`), `@longPress`, `@doubleTap`, `@change`, `@submit`, `@refresh`, `@endReached`. The value is a +public method name or `method(arg, ...)` with JSON arguments: `select('abc')`, `remove({{ $id }})`. The element's +own value is appended after your arguments: the text for `@submit` and `@change` on text inputs, a bool for +checkboxes and switches. Any element takes `@press`, including rows and columns. A misspelled event attribute is +dropped without an error. + +## Elements + +| Element | Props that matter | +|---|---| +| `column`, `row`, `stack`, `scroll-view`, `spacer`, `divider`, `pressable` | Tailwind `class`: `w-full h-full flex-1 gap-N p-N px-N items-center justify-between rounded-lg bg-theme-*` | +| `text` (slot is the text) | `class` (`text-lg font-bold line-through underline text-theme-on-surface`), `font` | +| `button` | label as slot or `label`; `variant` primary\|secondary\|destructive\|success\|ghost; `size` sm\|md\|lg; `icon`, `icon-trailing`, `ios-icon`, `android-icon`, `disabled`, `loading`, `a11y-label` | +| `outlined-text-input`, `filled-text-input`, `bare-text-input` | `native:model`, `placeholder`, `label`, `@submit`, `@change`, `keyboard` (text\|number\|decimal\|email\|phone\|url\|password), `secure`, `revealable`, `multiline`, `max-length`, `autofocus`, `leading-icon`, `trailing-icon`, `error`, `supporting` | +| `list` | `separator`, `plain`, `horizontal`, `on-refresh`, `on-end-reached`. Children: `list-item` or any element | +| `list-item` | see below | +| `icon` | `name` (`star.fill`, `trash`, `plus`), or per platform `ios="checkmark.circle.fill" android="check_circle"`, `:size="20"`, `class="text-theme-primary"` | +| `top-bar` | `title`, `subtitle`, `back`. Put it at the top level of the view | +| also | `toggle`, `checkbox`, `slider`, `select`, `radio-group`, `chip`, `badge`, `date-picker`, `modal`, `bottom-sheet`, `tab-row`, `progress-bar`, `activity-indicator` | + +There is no `text-input` element. It throws "Unknown native element type: text_input". + +## Text inputs + +```blade + +``` + +- Use `native:model.debounce.300ms` (`.debounce` alone is 300ms) or `.blur`. The default live mode syncs every + keystroke and echoes the value back into the field, which drops or reorders characters under fast typing. +- Take the text from `@submit` too. The handler gets it as its last argument, so a button tapped inside the + debounce window can't save a stale value: + +```php +public function save(?string $submitted = null): void +{ + $title = trim($submitted ?? $this->title); + // ... + $this->title = ''; // clears the field on the next render +} +``` + +- `keep-focus-on-submit` only works on iOS. + +## List items + +Props are written camelCase, exactly as below. Use `:prop` for PHP values. + +- Text: `headline`, `supporting`, `overline`, `headlineColor`. +- Leading slot, pick one: `leadingIcon`, `leadingCheckbox`, `leadingRadio`, `leadingMonogram`, `leadingAvatar`, + `leadingImage`. Changes go to `on-leading-change`. +- Trailing slot, pick one: `trailingIcon`, `trailingText`, `trailingCheckbox`, `trailingSwitch`, + `trailingIconButton`. Changes go to `on-trailing-change`; the icon button's press goes to `on-trailing-press`. +- Swipe: `:trailing-actions` and `:leading-actions` take arrays of `method`, `label`, `icon` (or `ios` and + `android`), `tint`, `role` (`destructive` makes it red). `on-swipe-delete` is the single-action shortcut. +- `@press` on the row, `disabled`, `native:key` for a stable identity. + +```blade + + @foreach ($notes as $note) + + @endforeach + +``` + +Swipe actions only work on list items that are direct children of ``. + +A list item can't strike through or restyle its headline. For that, build the row yourself inside a +`scroll-view`: + +```blade + + + @foreach ($notes as $note) + + + {{ $note->title }} + + + @endforeach + + +``` + +## Layout + +- `` gives a native navigation bar and handles the safe area. A screen can also return its title + from `navTitle(): string`. +- Add `safe-area` only to screens with no top bar, bottom nav or layout. +- Colours come from theme tokens (`bg-theme-*`, `text-theme-*`, `border-theme-*` with `primary`, `on-primary`, + `surface`, `on-surface`, `surface-variant`, `on-surface-variant`, `background`, `outline`), which switch for dark + mode on their own. + +## In tests + +Node types in `Native::test(...)->tree()` and `assertElement()` are snake_case: `list_item`, +`outlined_text_input`. A list item's checkbox state is `props.leading_checked`. `assertSee()` finds headlines and +swipe action labels. `press('remove(5)')` fires whatever callback was registered for that expression. diff --git a/.agents/skills/nativephp-mobile/SKILL.md b/.agents/skills/nativephp-mobile/SKILL.md new file mode 100644 index 0000000..cb4fd87 --- /dev/null +++ b/.agents/skills/nativephp-mobile/SKILL.md @@ -0,0 +1,560 @@ +--- +name: nativephp-mobile +description: "Builds fully native iOS and Android apps with PHP & Laravel. Activate when working with SuperNative screens (NativeComponent, Route::native, native:make), nested child components (component tags, props, key, emit, @event bindings), EDGE components (native:column, native:button, native:list, and 40+ more), composable chrome elements (top-bar, bottom-nav, fab, side-nav, bottom-bar) or NativeLayout chrome, native:model data binding, #[Computed]/#[Poll]/#[On] attributes, Native::test() component tests, native device APIs (camera, dialog, biometrics, scanner, geolocation, push notifications), NativePHP Artisan commands (native:run, native:install, native:watch, native:jump), build output paths (.app/.apk) and build traps, deep links, secure storage, or mobile app deployment." +--- + +# NativePHP Mobile v4 + +NativePHP Mobile v4 ("SuperNative") builds **fully native** apps: SwiftUI on iOS, Jetpack Compose on Android, +driven entirely by PHP. Each screen is a `NativeComponent` PHP class (think Livewire, but for native views) +rendering **EDGE** Blade elements. There is no web server and — for native UI screens — no web view. + +## Native UI First — Non-Negotiable + +**Every screen you build or scaffold must be native UI**: a `NativeComponent` + EDGE elements, registered with +`Route::native()`. + +- Never create new screens as web views, Livewire pages, or Inertia pages. The web view is a legacy escape hatch + (`native:web-view`) for embedding web content inside a native screen — never the foundation of one. +- If the user asks for a webview-based screen, build it natively with EDGE and briefly explain why (performance, + platform look-and-feel, no web-view lifecycle issues). Only fall back if they explicitly insist. +- When you encounter existing webview/Livewire/Inertia screens in an app, suggest migrating them — the + `nativephp-webview-to-native` skill walks through the conversion. +- Style exclusively with Tailwind utility classes via `class="..."` / `:class="..."`. Never inline CSS + `style="..."` or ad-hoc styling props. +- **Prefer theme tokens and font aliases over raw values.** Publish `config/native-ui.php` + (`vendor:publish --tag=native-ui-config`), define the palette in its `theme` block and semantic font + aliases in `fonts` (`'headline' => 'ArchivoNarrow-Bold'`), then style with `bg-theme-*` / `text-theme-*` / + `border-theme-*` classes and `font="headline"`. The token map is open-ended (add `success`, + `outline-variant`, … to both blocks and `bg-theme-success` just works) and theme classes accept opacity + modifiers (`bg-theme-primary/15` — the tonal-fill idiom). Arbitrary `bg-[#…]` values are only for genuine + data-driven color (category identity colors, imagery) and belong in one PHP home (enum/model), never inline + per view. +- Use `native:icon` for iconography (SF Symbols on iOS, Material Icons on Android — cross-platform names like + `home` resolve on both). Never use emoji characters in UI text, labels, or buttons unless the user explicitly + asks for them. Prefer the **typed icon enums** (`App\Icons\Ios`, `App\Icons\Android`, `App\Icons\AndroidOutlined`, + bound with `:ios` / `:android` — they're autocompletable and can't misspell a symbol name. The enums are + generated, not shipped: **if `app/Icons/` doesn't exist yet, run `php artisan native-ui:generate-icons` + first** (safe to run yourself; re-run with `--refresh-material` to update). Import them with `@use` (compiled + views have no namespace), or use fully-qualified cases: + + ```blade + @use('App\Icons\Ios') + @use('App\Icons\Android') + + + ``` + +## Documentation + +Before implementing any feature, fetch the relevant docs using `WebFetch`. Find the right URL in +[references/available-docs.md](references/available-docs.md). + +``` +WebFetch("https://nativephp.com/docs/mobile/4/the-basics/routing", "Explain Route::native, navigation methods, and transitions") +``` + +## Build Commands — Run Them Yourself + +Check behaviour with `Native::test()` first (see Testing). When a change needs a build to take effect or to be +checked, run `native:run` yourself against a booted simulator or running emulator. The details, output paths and +traps are under Building and Running below. If no simulator or emulator is available, say so and give the user +the command. + +```bash +php artisan native:run ios --no-tty -n # or android ; build, install, launch, then exit +php artisan native:run ios --watch # build, deploy, hot reload: never exits +php artisan native:watch # hot reload only: never exits +php artisan native:jump # device dev loop via the Jump app (QR code) +./native run # shortcut wrapper installed by native:install +``` + +Ask first, or leave to the user: `--watch` and `native:watch` never exit, so don't block on them (start one in the +background only when the user wants hot reload). Release builds, signing, `native:package` and store uploads are +the user's call. + +For a build-and-verify loop with machine-readable output (`native:run ... --json`, `native:devices`, +`native:status`, `native:screenshot`, `native:tail`, `native:open-url`), follow the `nativephp-agent-loop` skill. + +The Vite dev server is **opt-in** in v4: add `--vite` to `native:run`/`native:watch` only when the app uses +JS/CSS HMR (web-view assets). Native UI screens hot-reload without Vite. `npm run build -- --mode=ios|android` +is only needed for apps that still ship web-view assets. + +## Getting Started + +New app from the starter kit: + +```bash +laravel new my-app --using=nativephp/mobile-starter --no-node +``` + +The starter already has `nativephp/mobile-ui` installed and registered in `app/Providers/NativeServiceProvider.php`, +a `routes/mobile.php`, an example `app/NativeComponents/Home.php` with `tests/Feature/NativeHomeTest.php`, Pest, +and it has run `native:install` for you. When you replace the Home screen, delete or rewrite that test (it asserts +the welcome text). + +Existing Laravel app: + +```bash +composer require nativephp/mobile nativephp/mobile-ui +php artisan vendor:publish --tag=nativephp-plugins-provider # creates app/Providers/NativeServiceProvider.php +php artisan native:plugin:register nativephp/mobile-ui +php artisan native:plugin:list # must show mobile-ui as registered +php artisan native:install both # after setting the .env keys below +``` + +Then create `routes/mobile.php` (it is loaded automatically). `mobile-ui` is not optional: core has no renderers, +so every element, even `column` and `text`, comes from it. + +Set env vars **before** `php artisan native:install`: + +```dotenv +APP_NAME="My App" # the display name on both platforms +NATIVEPHP_APP_ID=com.yourcompany.yourapp +NATIVEPHP_APP_VERSION="DEBUG" # the version number, e.g. 1.2.0 +NATIVEPHP_APP_VERSION_CODE="1" # the build number +# Optional for iOS: +NATIVEPHP_DEVELOPMENT_TEAM=XXXXXXXXXX +``` + +The name, app ID and version are applied again on every build, so they can be changed later. Keep +`NATIVEPHP_APP_VERSION=DEBUG` while developing (see Building and Running below). + +OS support: macOS builds iOS + Android; Windows/Linux build Android only; WSL unsupported. + +## SuperNative Screens + +Scaffold with `php artisan native:make Counter` (remove with `native:rm`). Register screens in +`routes/mobile.php`. The package loads it automatically, but only in native contexts (on device, under Jump, +in `native:*` commands and in tests), so a web deploy of the same app never exposes them: + +```php +Route::native('/', Home::class); +Route::native('/item/{id}', ItemDetail::class); +``` + +If the app already loads `routes/mobile.php` itself, the package leaves it alone and it isn't gated. Remove that +registration to get the native-only behaviour. + +Inside a `NativeComponent`: `$this->param('id')`, `$this->data('key', 'default')`, `$this->navigate('/item/42')`, +`$this->back()`, `$this->replace('/login')`, `$this->exitToWeb('/dashboard')`; chain +`->transition(Transition::SlideFromBottom)` to customize animation. In Blade, `@navigate='/path'` works on any +element (modifiers: `@navigate.back`, `@navigate.replace.fade`, `@navigate.slideFromBottom`). Use single quotes +for a plain route; double quotes hold a PHP expression, so `@navigate="/path"` fails to compile. Build dynamic +routes in PHP: `@navigate="'/item/' . $item->id"`. + +Lifecycle hooks: `mount()` (first push only), `onResume()` (returning to the screen), `onBackPressed()` +(Android back button), `unmount()`, and `updated{Property}()` when a bound property changes. Mark a component +`#[Lazy]` to paint a placeholder instantly while a slow `mount()` runs in the background. + +### A complete screen + +`php artisan native:make Notes` writes the class and `resources/views/native/notes.blade.php`. Public properties +are view variables and `native:model` targets. `render()` runs again after every handler call. + +```php +namespace App\NativeComponents; + +use App\Models\Note; +use Illuminate\View\View; +use Native\Mobile\Edge\NativeComponent; + +class Notes extends NativeComponent +{ + public string $title = ''; + + // @submit passes the field's text as the last argument, so a stale bound value can't lose input. + public function save(?string $submitted = null): void + { + $title = trim($submitted ?? $this->title); + if ($title === '') { + return; + } + Note::create(['title' => $title]); + $this->title = ''; // clears the bound field on the next render + } + + public function pin(int $id, bool $checked): void { Note::whereKey($id)->update(['pinned' => $checked]); } + + public function remove(int $id): void { Note::whereKey($id)->delete(); } + + public function render(): View + { + return view('native.notes', ['notes' => Note::orderBy('id')->get()]); + } +} +``` + +```blade + + + + + + Add + + + + @foreach ($notes as $note) + + @endforeach + + +``` + +Handler values are a method name or `method(arg, ...)`. Arguments are parsed as JSON, so quote strings: +`select('abc')`, `remove({{ $id }})`. The event's own value is appended after your arguments: the text for +`@submit`/`@change` on text inputs, a bool for checkbox and switch changes. Any element takes `@press`, including +rows and columns. For element props (list items, swipe actions, text inputs, buttons) activate the +`nativephp-mobile-ui` skill, which ships with `nativephp/mobile-ui`. + +## EDGE Elements + +Screens are built from `native:` Blade components (the prefix is optional but preferred for clarity): + +```blade + + Welcome + + + +``` + +The elements and their renderers come from the `nativephp/mobile-ui` plugin. Core has no renderers of its +own, so even `column` and `text` need it. Install and register it before building any screen: +`composer require nativephp/mobile-ui`, then `php artisan native:plugin:register nativephp/mobile-ui` (this +adds `NativeUIServiceProvider` to `plugins()` in `app/Providers/NativeServiceProvider.php`). Check with +`php artisan native:plugin:list`. If it is installed but not registered, bare tags like `