[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M7CZDDSPCYKN01NHBB3F4XYP":3,"skill-same:01M7CZDDSPCYKN01NHBB3F4XYP":60},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":15,"categories":16,"keywords":17,"publishedAt":18,"linkOnly":19,"markdownContent":20,"markdownBody":21,"frontMatter":22,"refName":32,"commitSha":33,"skillDirectory":34,"forksCount":35,"repositoryHtmlUrl":30,"repositoryHomepageUrl":6,"ownerHtmlUrl":36,"ownerBlogUrl":37,"ownerDescription":38,"updatedAt":39,"install":40,"resources":53},"01M7CZDDSPCYKN01NHBB3F4XYP","padosoft-laravel-conventions",null,"Use this skill when writing or reviewing Laravel\u002FPHP code — a controller, a FormRequest, a service, a job, a migration, an Eloquent query, a model event, a queued or bulk operation — and whenever a symptom shows up: a controller that grew into the business logic, an N+1 found in the logs, a bulk command that runs out of memory, a job that retries something it should not, a soft-deleted row reappearing in a count, a model event that fires on a mass update and does not. It applies to any Laravel version: the rules are about the shape of the application. Do not use it for a security review (padosoft-laravel-security-review), for what goes in a log (padosoft-logging-discipline), or for infrastructure and deployment.","padosoft\u002Fskills","padosoft","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F10467753?v=4","01M7CZ3FRSM851DK225E3KK2VF","01M7CZ3FSY016E21VS6EABM21V",1,"MIT","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpadosoft-laravel-conventions\u002FSKILL.md",[],[],"2026-11-15 14:19:17",false,"---\nname: padosoft-laravel-conventions\ndescription: >-\n  Use this skill when writing or reviewing Laravel\u002FPHP code — a controller, a FormRequest, a service, a job,\n  a migration, an Eloquent query, a model event, a queued or bulk operation — and whenever a symptom shows\n  up: a controller that grew into the business logic, an N+1 found in the logs, a bulk command that runs out\n  of memory, a job that retries something it should not, a soft-deleted row reappearing in a count, a model\n  event that fires on a mass update and does not. It applies to any Laravel version: the rules are about the\n  shape of the application. Do not use it for a security review (padosoft-laravel-security-review),\n  for what goes in a log (padosoft-logging-discipline), or for infrastructure and deployment.\nlicense: MIT\ncompatibility: >-\n  Any Laravel version. The rules are about how an application is shaped, not about framework features;\n  where a version moved a file rather than changing a rule, the text says so.\nmetadata:\n  version: 0.5.0\n  author: Padosoft\n  summary: Where the logic lives and what crosses which boundary, on any framework version.\n  profiles: laravel\n  scope: project\n  repository: https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\n  keywords: laravel, php, eloquent, service, dto, job, queue, migration, n+1, architecture\n---\n\n# Laravel conventions\n\n**None of this depends on a framework or language version.** These are rules about how the application is\nshaped — where the logic lives, what crosses a boundary, what the database is asked to do — and they were\nearned on codebases several major versions apart. A rule that only held on one version would not be a rule,\nit would be a release note.\n\nFor a **new** project, start from the current Laravel and PHP, a formatter and a static analyser, and the\ntest framework the repository already chose. On an **existing** codebase apply the same rules with that\nproject's idiom, and do not mix a new idiom with the legacy one halfway through a file — a file that does\nboth is harder to read than a file that is consistently old.\n\nWhere a version genuinely moved something it is noted inline. In every one of those cases what moved was the\n*file*, not the rule.\n\n## Contents\n\n1. The flow · 2. Long or asynchronous work · 3. Structure · 4. Eloquent and queries (4b. the builder layer)\n· 5. Migrations · 6. Model events · 7. Types, null, errors, untrusted data, package defaults (7b. Providers and\nthe container) · 8. Code shape · 9. Files and storage · 10. Failed jobs · Gotchas · Checklist\n\n---\n\n## 1. The flow: FormRequest → DTO → Service → Resource\n\nFor any endpoint or form that is not trivial:\n\n1. **`FormRequest`** validates and normalises the HTTP input;\n2. the **controller** builds an explicit **DTO**;\n3. the **service** (or action) runs the application logic;\n4. the **controller** turns the outcome into a response, redirect or `JsonResource`.\n\nWhat each step buys: the data contract stops being an untyped array crossing boundaries, the service is\ntestable without HTTP, and the controller has one job — translating.\n\n**The controller never contains business logic.** The signal it has drifted: it queries, it decides, it\nformats. Two of the three belong elsewhere.\n\nNever pass `$request->all()` down: pass `validated()`, or better the DTO. An array that \"came from the\nrequest\" has no shape anyone can rely on three files later.\n\n## 2. Long or asynchronous work: DTO → Service → Job\n\n- **DTO \u002F value object** for the input;\n- **service \u002F action** for the logic;\n- **job** for queued execution.\n\n**The job orchestrates, it does not implement.** Retry, timeout, backoff and execution context live in the\njob; the reusable logic lives in the service, so it can be called synchronously by a command or a test.\n\nIn a job, distinguish a **retryable** error from a **permanent** one. Retrying a validation failure burns the\nqueue; not retrying a timeout loses work. A permanent failure fails the job explicitly rather than throwing\nsomething the queue will retry sixteen times.\n\n## 3. Structure\n\n```\nDomain\u002F\u003CModule>\u002F\n├── Dto\u002F                 explicit inputs\n├── Http\u002FRequests\u002F       HTTP validation\n├── Http\u002FControllers\u002F\n├── Services\u002F  (or Actions\u002F)\n├── Jobs\u002F\n└── Routes\u002F              if the module exposes its own endpoints\n```\n\nSymmetrical directories: controller, request, service and **test** follow each other. No bin directories —\n`misc`, `common`, `utils`, `various` — and no omnivorous generic service. When a folder stops having one\nresponsibility, split it.\n\n## 4. Eloquent and queries\n\n- **N+1**: eager load, or write a dedicated query. It is the single most common performance defect, and it\n  only shows up with production-sized data.\n- Need one value? Do not hydrate a whole model — `value()`, `pluck()`, an aggregate.\n- **Never `select *`** on a critical query over a large dataset.\n- Before micro-optimising, **measure**: cardinality and the execution plan. An index added by intuition is\n  often an index that is never used.\n- **`chunkById` or `cursor` for bulk**, never `get()` followed by filtering in PHP. And push the filter into\n  SQL: `whereNotIn` with chunked arrays beats loading everything and rejecting it in memory.\n- **Soft deletes**: a query that must ignore them says so explicitly. A count that silently includes trashed\n  rows is a number nobody can reproduce.\n- **Date-range filters are half-open.** A date-only upper bound means the start of that day, so `\u003C= to`\n  drops the whole last day. Filter on `>= start of from` and `\u003C start of (to + 1 day)`. Do not use\n  `whereDate`: it wraps the column in a function and disables its index (**`padosoft-database-design`**\n  §4), and the half-open range on the raw column fixes both. The date cast looks correct and the function\n  wrap is hidden inside the helper, which is why this one is so often written wrong.\n\n`chunkById` and not `chunk` when the loop **modifies** the rows it iterates: `chunk` pages by offset, so\nupdating rows shifts the window and silently skips records.\n\n## 4b. Put the query language in a builder layer, not in scopes\n\nModel scopes spread query logic across the model, the controller and whatever else reached for it. A\ndedicated query-builder class per aggregate keeps it in one place and makes it composable. The convention\nthat makes such a layer survive a few hundred classes:\n\n| Kind of method | Returns | Named |\n|---|---|---|\n| Building block | the builder itself, chainable | `whereX()`, `ifWhereX()` (conditional), `joinX()`, `orderByX()`, `withX()` |\n| Composition | the builder | a domain phrase: `visibleInCatalogue()`, built **only** by chaining building blocks |\n| Complete query | a collection, a model, a paginator, a count | `getX()`, `paginateX()`, `countX()` |\n\nThree prohibitions, and they are what keeps the layer honest:\n\n- **No ambient state inside a builder.** Reading the current tenant, locale or a global setting from inside\n  a `where` makes the method untestable and its result dependent on something the caller cannot see. Take\n  it as a parameter.\n- **No side effects.** A builder builds queries: no state changes, no mail, no dispatch, no API calls.\n- **No scopes on the models**, once the layer exists. Two places to look is worse than either one.\n\nWhen a builder passes roughly a hundred methods, split it by domain into traits — a few dozen methods each,\na handful of traits — rather than letting one class grow past reading size.\n\n**Check for an existing helper before writing query logic by hand.** A project that has accumulated\nconditional-clause and formatting helpers has them precisely so the same chain is not re-implemented with a\nsubtly different edge case; and when the logic is reusable and the helper does not exist, the move is to add\nit, not to inline it for the third time.\n\n## 5. Migrations and schema\n\n- One table, one responsibility. No column encoding two concepts.\n- Indexes follow the **real read patterns**: if a hot query filters and sorts on the same fields, model the\n  index on that.\n- Think about cardinality, unique constraints and nullability deliberately — nullable by default is a\n  decision nobody made.\n- Foreign keys where the stack allows them.\n- Derived or denormalised data: **document the source of truth** next to it, or the copy becomes the truth by\n  accident.\n- Index selection, partitioning, JSON columns and the guard clauses that make a migration re-runnable\n  against a schema that does not match the ledger: **`padosoft-database-design`**.\n- A migration is run once on production and lives forever in the history: make it idempotent where the\n  project's convention requires it, and never edit one that has shipped.\n\n## 6. Model events\n\nThey fire on **model** operations, not on query-builder mass operations: `Model::where(...)->update([...])`\ndoes **not** fire `updating`\u002F`updated`. That asymmetry is the bug — a rule enforced in an event silently does\nnot apply to the bulk path.\n\nSo: either the invariant lives somewhere both paths cross (a database constraint, an observer plus an\nexplicit call on the bulk path), or the bulk path is banned for that table and the ban is written down.\n\nAn event that dispatches a job must not assume the transaction committed: use the after-commit dispatch, or\nthe job runs against a row that is not there yet.\n\n## 7. Types, null and errors\n\n- **Type hints everywhere**: parameters, return types, properties. Whatever the language version allows,\n  use all of it — an untyped boundary is where the null gets in.\n- Prefer an explicit object to a \"magic\" helper when it makes the contract clearer.\n- **Do not use exceptions for expected user-validation flows** — that is what validation is for. Exceptions\n  are for what should not happen.\n- Translate infrastructure errors into application-level messages; what may and may not appear in them is in\n  **`padosoft-laravel-security-review`** (`SEC-ERRLEAK-001`), and what goes in the log is in\n  **`padosoft-logging-discipline`**.\n- Null safety: a nullable that reaches a calculation makes a wrong number, not a crash. Decide at the\n  boundary — reject it, default it, or make the type non-nullable — never three files downstream.\n\n### The null-safety specifics that keep recurring\n\n- **A find that returns null, followed by a property access.** Either use the failing variant when absence\n  is a 404, or return early — never let the next line deal with it.\n- **A chain of two calls where one is optional.** Use the null-safe operator with an explicit default, or\n  assign to a variable and check it. The return type declares whether it can be null; read it.\n- **Loose equality with null, zero or the empty string** is a coin toss: the type juggling makes several of\n  them equal to each other. Compare strictly, and cast deliberately when a legacy value really is a string.\n- **A date parser given null returns \"now\"** in more than one library. That is not a crash, it is a wrong\n  value that looks plausible for exactly as long as it takes to reach a customer.\n\n\nFour more that keep a package honest:\n\n- **Make the illegal state unrepresentable.** When two fields are only valid together — a blocked verdict\n  with no reason, an accepted amount with no currency — make the constructor private and expose named\n  constructors for the valid combinations. A validation rule can be forgotten; a constructor that does not\n  exist cannot be called.\n- **A misconfiguration that opens a surface fails at boot.** Warn when a feature is enabled and still\n  resolves to its no-op implementation; **throw** when something is exposed with an empty guard list. The\n  difference is whether the wrong configuration is merely useless or actively unsafe.\n- **Declared but unwired is a defect.** A config key, toggle, DTO field or schema column that nothing reads,\n  or that is read and not honoured, is dead configuration: someone changes it and nothing happens. Every\n  toggle changes behaviour where it is bound — for example by binding a no-op implementation when it is off\n  — and a key nothing consults is deleted, not kept for later.\n- **Routes shipped by a package default to the stateless middleware group**, not the session one, which may\n  not even be registered in the host's test context. Put authentication on the privileged routes and let\n  the application add the session group where sessions exist.\n- **A package route carries its own prerequisites.** It must not name a limiter or middleware that only the\n  host defines: a missing named limiter throws when the request arrives, not at boot. Register the\n  package's own default and let the host substitute it explicitly, with a binding it can override.\n\nChanging a signature or a return type in a hierarchy is its own procedure: **`padosoft-contract-changes`**.\nDeciding a branch by environment name is another: **`padosoft-environment-gating`**.\n\n### Untrusted structured data: decoded JSON, webhook bodies, model output\n\nValidate the type, then the shape, and only then use the value. Three casts that look harmless:\n\n- **`json_decode($s, true)` cannot tell `{}` from `[]`.** Both become an empty array, so \"an object with no\n  keys\" and \"a list with no items\" are the same value. Where the difference matters, decode that field\n  without the associative flag, or check the raw text first.\n- **A shallow `(array)` cast leaves nested objects in place.** The next level still holds objects, and the\n  array access on it fails later. Decode associatively, or convert recursively.\n- **A bare `(string)` cast turns an array into `\"Array\"`, and an `(int)` cast into 0 or 1.** `\"Array\"`\n  passes a non-empty check. Test `is_string` \u002F `is_int` first, then the keys, then use it.\n\n**Return the reason for the failure, not a boolean.** A caller that retries — a loop that feeds the error\nback to a model, a re-queued job — only improves when the feedback says which field was the wrong type.\n\n### Lenient parsing of config and `fromArray` inputs\n\n- **A default applies only when the key is absent.** Test with `array_key_exists`, never `??`: `??` treats\n  an explicit `null` as absent, so a cleared or mistyped value silently turns into the default. An explicit\n  `null` is invalid, and says so.\n- **Closed key sets are validated.** A map keyed by an enum, or a list of required cases, is checked for\n  unknown and for missing keys, and for being a list or a map as declared — an empty array is both.\n- **Env-derived scalars are parsed once**, by one parser that every reader calls. They arrive as strings:\n  `(bool) \"false\"` is true. Two readers parsing the same variable two ways is how a toggle is on in one\n  place and off in another.\n\n## 7b. Providers and the container\n\n- **A global bind or override does not reach a contextual binding of the same abstract.** A consumer with a\n  per-consumer binding keeps its own instance, so override both. Do it in `boot()`, after every\n  package's `register()` has run, or the package's own binding wins. The type hints are identical, the\n  wrong instance is injected, and nothing errors.\n- **A wrapper that carries one consumer's identity is inherited by the next consumer.** If a binding\n  decorates the implementation with a name, tenant or channel, every later consumer of that interface gets\n  the same decorated instance. Build the wrapper per consumer, or bind it contextually.\n- **`mergeConfigFrom()` merges one level deep, and the application's value wins.** A nested array the\n  application sets replaces the package's whole nested array, so the sibling defaults inside it disappear\n  without an error. When both the application's values and the package's nested defaults must survive,\n  merge that level explicitly instead of trusting the shallow merge.\n- **Check that an optional dependency is bound before resolving it, then let resolution fail loudly.** Ask\n  `bound()` first and resolve outside any `try`. Do not catch the container's binding-resolution exception\n  to mean \"not installed\": it is also thrown when a bound service has a constructor dependency that cannot\n  be resolved, and a `catch (Throwable)` swallows a missing extension on top of that. Either way the feature\n  quietly runs without a component that is installed but misconfigured.\n\n## 8. Code shape\n\nGuard clauses and early return; avoid `else` when a return makes the flow obvious. Small methods, one main\nresponsibility. Complex branches move into private methods or dedicated services. Comment decisions,\nconstraints and trade-offs — not the obvious.\n\n\nFour more, and the first one is the one people argue about:\n\n- **A variable holding a database field keeps the field's name.** Renaming it on the way in breaks the only\n  link between the row and the code, and makes the search that would have found every use return nothing.\n  Add a suffix when the variable means something narrower than the column, and keep the column's spelling\n  underneath it. Free naming is for values that are not a field.\n- **Display formatting has one home.** A presenter, a view model, a formatter — the name matters less than\n  the fact that there is exactly one, and that neither the model nor the template formats anything itself.\n  Otherwise the same value is rendered three ways in three screens and nobody can say which is right.\n- **Settings are a namespace, not a flat bag.** One root prefix, then area, then parameter; and a\n  convention in the name that says what kind of setting it is — a toggle reads as a toggle. A flat list of\n  a few hundred keys is a list nobody greps successfully.\n- **Directory and file naming is a convention, so it is one convention.** Two spellings in the same tree\n  means every path is a guess, and on a case-insensitive filesystem it also means it works locally and\n  fails on the server.\n\nAnti-patterns, in the order they appear: a 150-line method with several responsibilities; business logic\nmixed with I\u002FO or rendering; a boolean flag that changes what a method fundamentally does; names like `data`,\n`tmp`, `manager`, `utils` with no context.\n\n## 9. Files and storage\n\nStreams and chunks for large files, never the whole thing in memory. Validate type, size and destination\n**before** copying. No whole-export concatenation in RAM. Clean up temporary files and intermediate\nartefacts — including on the failure path, which is where they accumulate.\n\n---\n\n## 10. Failed jobs are a subsystem, not a table\n\nA job that exhausts its retries and lands in the failed table has failed **silently** unless something\nnotices. Give every job a common base that, on final failure, notifies — with the retry count and the\nbackoff as declared properties, and recipients and templates overridable per job for the ones that matter.\n\nThe question to answer for each job: **who finds out, and how long after?** If the answer is \"whoever\nhappens to look at the dashboard\", it is not a subsystem. See **`padosoft-failure-visibility`** and\n**`padosoft-durable-effects`**.\n\n## Gotchas\n\n- **`chunk` while updating skips rows.** Use `chunkById`.\n- **Mass updates bypass model events** (§6), and so do mass deletes and `upsert`.\n- **A `FormRequest` validating does not make `all()` safe**: it returns everything that was sent.\n- **Eager loading inside a loop is still N+1**, just harder to see.\n- **An index on a low-cardinality column often does nothing**; measure before adding.\n- **A job retried after a partial write repeats the write.** Idempotency is designed in, not hoped for.\n- **A global override does not reach a contextual binding** (§7b): the right type is injected, the wrong\n  instance behind it.\n- **`??` as the default for an optional key swallows an explicit `null`**, and a bare cast on decoded JSON\n  lets `\"Array\"` through (§7).\n- **`\u003C= $to` or `whereDate` on a date-only bound** loses the last day or the index (§4).\n- **`dd()` and `dump()` in committed code** — see `padosoft-logging-discipline` §3, and do not delete\n  someone else's silently: report it.\n\n## Checklist\n\n- [ ] Controller translates; logic in the service; DTO across boundaries\n- [ ] Job orchestrates, service implements; retryable vs permanent distinguished\n- [ ] No N+1; no `select *` on hot paths; bulk through `chunkById`\u002F`cursor` with filters in SQL\n- [ ] Soft-delete intent explicit in queries that care\n- [ ] Migration: responsibility, indexes on real patterns, nullability decided, source of truth documented\n- [ ] Bulk paths that bypass model events identified and handled\n- [ ] Full type hints; nullability resolved at the boundary\n- [ ] Decoded external data type- and shape-checked before use; date ranges half-open\n- [ ] Every config key, toggle and DTO field is read and honoured where it is bound; overrides cover contextual bindings\n- [ ] Pint and static analysis clean\n\n## Final report\n\n```\nChange: \u003Cwhat>  ·  Laravel \u003Cversion> \u002F PHP \u003Cversion>\nFlow: FormRequest \u003Cfile> → DTO \u003Cfile> → Service \u003Cfile> → Resource \u003Cfile>\nQueries: N+1 checked | bulk strategy \u003CchunkById|cursor|none needed>\nMigration: \u003Cyes\u002Fno — indexes, nullability, source of truth>\nModel events: bulk path \u003Cnot used | handled how>\nPint \u002F static analysis: PASS | FAIL \u003Cdetail>\n```\n","# Laravel conventions\n\n**None of this depends on a framework or language version.** These are rules about how the application is\nshaped — where the logic lives, what crosses a boundary, what the database is asked to do — and they were\nearned on codebases several major versions apart. A rule that only held on one version would not be a rule,\nit would be a release note.\n\nFor a **new** project, start from the current Laravel and PHP, a formatter and a static analyser, and the\ntest framework the repository already chose. On an **existing** codebase apply the same rules with that\nproject's idiom, and do not mix a new idiom with the legacy one halfway through a file — a file that does\nboth is harder to read than a file that is consistently old.\n\nWhere a version genuinely moved something it is noted inline. In every one of those cases what moved was the\n*file*, not the rule.\n\n## Contents\n\n1. The flow · 2. Long or asynchronous work · 3. Structure · 4. Eloquent and queries (4b. the builder layer)\n· 5. Migrations · 6. Model events · 7. Types, null, errors, untrusted data, package defaults (7b. Providers and\nthe container) · 8. Code shape · 9. Files and storage · 10. Failed jobs · Gotchas · Checklist\n\n---\n\n## 1. The flow: FormRequest → DTO → Service → Resource\n\nFor any endpoint or form that is not trivial:\n\n1. **`FormRequest`** validates and normalises the HTTP input;\n2. the **controller** builds an explicit **DTO**;\n3. the **service** (or action) runs the application logic;\n4. the **controller** turns the outcome into a response, redirect or `JsonResource`.\n\nWhat each step buys: the data contract stops being an untyped array crossing boundaries, the service is\ntestable without HTTP, and the controller has one job — translating.\n\n**The controller never contains business logic.** The signal it has drifted: it queries, it decides, it\nformats. Two of the three belong elsewhere.\n\nNever pass `$request->all()` down: pass `validated()`, or better the DTO. An array that \"came from the\nrequest\" has no shape anyone can rely on three files later.\n\n## 2. Long or asynchronous work: DTO → Service → Job\n\n- **DTO \u002F value object** for the input;\n- **service \u002F action** for the logic;\n- **job** for queued execution.\n\n**The job orchestrates, it does not implement.** Retry, timeout, backoff and execution context live in the\njob; the reusable logic lives in the service, so it can be called synchronously by a command or a test.\n\nIn a job, distinguish a **retryable** error from a **permanent** one. Retrying a validation failure burns the\nqueue; not retrying a timeout loses work. A permanent failure fails the job explicitly rather than throwing\nsomething the queue will retry sixteen times.\n\n## 3. Structure\n\n```\nDomain\u002F\u003CModule>\u002F\n├── Dto\u002F                 explicit inputs\n├── Http\u002FRequests\u002F       HTTP validation\n├── Http\u002FControllers\u002F\n├── Services\u002F  (or Actions\u002F)\n├── Jobs\u002F\n└── Routes\u002F              if the module exposes its own endpoints\n```\n\nSymmetrical directories: controller, request, service and **test** follow each other. No bin directories —\n`misc`, `common`, `utils`, `various` — and no omnivorous generic service. When a folder stops having one\nresponsibility, split it.\n\n## 4. Eloquent and queries\n\n- **N+1**: eager load, or write a dedicated query. It is the single most common performance defect, and it\n  only shows up with production-sized data.\n- Need one value? Do not hydrate a whole model — `value()`, `pluck()`, an aggregate.\n- **Never `select *`** on a critical query over a large dataset.\n- Before micro-optimising, **measure**: cardinality and the execution plan. An index added by intuition is\n  often an index that is never used.\n- **`chunkById` or `cursor` for bulk**, never `get()` followed by filtering in PHP. And push the filter into\n  SQL: `whereNotIn` with chunked arrays beats loading everything and rejecting it in memory.\n- **Soft deletes**: a query that must ignore them says so explicitly. A count that silently includes trashed\n  rows is a number nobody can reproduce.\n- **Date-range filters are half-open.** A date-only upper bound means the start of that day, so `\u003C= to`\n  drops the whole last day. Filter on `>= start of from` and `\u003C start of (to + 1 day)`. Do not use\n  `whereDate`: it wraps the column in a function and disables its index (**`padosoft-database-design`**\n  §4), and the half-open range on the raw column fixes both. The date cast looks correct and the function\n  wrap is hidden inside the helper, which is why this one is so often written wrong.\n\n`chunkById` and not `chunk` when the loop **modifies** the rows it iterates: `chunk` pages by offset, so\nupdating rows shifts the window and silently skips records.\n\n## 4b. Put the query language in a builder layer, not in scopes\n\nModel scopes spread query logic across the model, the controller and whatever else reached for it. A\ndedicated query-builder class per aggregate keeps it in one place and makes it composable. The convention\nthat makes such a layer survive a few hundred classes:\n\n| Kind of method | Returns | Named |\n|---|---|---|\n| Building block | the builder itself, chainable | `whereX()`, `ifWhereX()` (conditional), `joinX()`, `orderByX()`, `withX()` |\n| Composition | the builder | a domain phrase: `visibleInCatalogue()`, built **only** by chaining building blocks |\n| Complete query | a collection, a model, a paginator, a count | `getX()`, `paginateX()`, `countX()` |\n\nThree prohibitions, and they are what keeps the layer honest:\n\n- **No ambient state inside a builder.** Reading the current tenant, locale or a global setting from inside\n  a `where` makes the method untestable and its result dependent on something the caller cannot see. Take\n  it as a parameter.\n- **No side effects.** A builder builds queries: no state changes, no mail, no dispatch, no API calls.\n- **No scopes on the models**, once the layer exists. Two places to look is worse than either one.\n\nWhen a builder passes roughly a hundred methods, split it by domain into traits — a few dozen methods each,\na handful of traits — rather than letting one class grow past reading size.\n\n**Check for an existing helper before writing query logic by hand.** A project that has accumulated\nconditional-clause and formatting helpers has them precisely so the same chain is not re-implemented with a\nsubtly different edge case; and when the logic is reusable and the helper does not exist, the move is to add\nit, not to inline it for the third time.\n\n## 5. Migrations and schema\n\n- One table, one responsibility. No column encoding two concepts.\n- Indexes follow the **real read patterns**: if a hot query filters and sorts on the same fields, model the\n  index on that.\n- Think about cardinality, unique constraints and nullability deliberately — nullable by default is a\n  decision nobody made.\n- Foreign keys where the stack allows them.\n- Derived or denormalised data: **document the source of truth** next to it, or the copy becomes the truth by\n  accident.\n- Index selection, partitioning, JSON columns and the guard clauses that make a migration re-runnable\n  against a schema that does not match the ledger: **`padosoft-database-design`**.\n- A migration is run once on production and lives forever in the history: make it idempotent where the\n  project's convention requires it, and never edit one that has shipped.\n\n## 6. Model events\n\nThey fire on **model** operations, not on query-builder mass operations: `Model::where(...)->update([...])`\ndoes **not** fire `updating`\u002F`updated`. That asymmetry is the bug — a rule enforced in an event silently does\nnot apply to the bulk path.\n\nSo: either the invariant lives somewhere both paths cross (a database constraint, an observer plus an\nexplicit call on the bulk path), or the bulk path is banned for that table and the ban is written down.\n\nAn event that dispatches a job must not assume the transaction committed: use the after-commit dispatch, or\nthe job runs against a row that is not there yet.\n\n## 7. Types, null and errors\n\n- **Type hints everywhere**: parameters, return types, properties. Whatever the language version allows,\n  use all of it — an untyped boundary is where the null gets in.\n- Prefer an explicit object to a \"magic\" helper when it makes the contract clearer.\n- **Do not use exceptions for expected user-validation flows** — that is what validation is for. Exceptions\n  are for what should not happen.\n- Translate infrastructure errors into application-level messages; what may and may not appear in them is in\n  **`padosoft-laravel-security-review`** (`SEC-ERRLEAK-001`), and what goes in the log is in\n  **`padosoft-logging-discipline`**.\n- Null safety: a nullable that reaches a calculation makes a wrong number, not a crash. Decide at the\n  boundary — reject it, default it, or make the type non-nullable — never three files downstream.\n\n### The null-safety specifics that keep recurring\n\n- **A find that returns null, followed by a property access.** Either use the failing variant when absence\n  is a 404, or return early — never let the next line deal with it.\n- **A chain of two calls where one is optional.** Use the null-safe operator with an explicit default, or\n  assign to a variable and check it. The return type declares whether it can be null; read it.\n- **Loose equality with null, zero or the empty string** is a coin toss: the type juggling makes several of\n  them equal to each other. Compare strictly, and cast deliberately when a legacy value really is a string.\n- **A date parser given null returns \"now\"** in more than one library. That is not a crash, it is a wrong\n  value that looks plausible for exactly as long as it takes to reach a customer.\n\n\nFour more that keep a package honest:\n\n- **Make the illegal state unrepresentable.** When two fields are only valid together — a blocked verdict\n  with no reason, an accepted amount with no currency — make the constructor private and expose named\n  constructors for the valid combinations. A validation rule can be forgotten; a constructor that does not\n  exist cannot be called.\n- **A misconfiguration that opens a surface fails at boot.** Warn when a feature is enabled and still\n  resolves to its no-op implementation; **throw** when something is exposed with an empty guard list. The\n  difference is whether the wrong configuration is merely useless or actively unsafe.\n- **Declared but unwired is a defect.** A config key, toggle, DTO field or schema column that nothing reads,\n  or that is read and not honoured, is dead configuration: someone changes it and nothing happens. Every\n  toggle changes behaviour where it is bound — for example by binding a no-op implementation when it is off\n  — and a key nothing consults is deleted, not kept for later.\n- **Routes shipped by a package default to the stateless middleware group**, not the session one, which may\n  not even be registered in the host's test context. Put authentication on the privileged routes and let\n  the application add the session group where sessions exist.\n- **A package route carries its own prerequisites.** It must not name a limiter or middleware that only the\n  host defines: a missing named limiter throws when the request arrives, not at boot. Register the\n  package's own default and let the host substitute it explicitly, with a binding it can override.\n\nChanging a signature or a return type in a hierarchy is its own procedure: **`padosoft-contract-changes`**.\nDeciding a branch by environment name is another: **`padosoft-environment-gating`**.\n\n### Untrusted structured data: decoded JSON, webhook bodies, model output\n\nValidate the type, then the shape, and only then use the value. Three casts that look harmless:\n\n- **`json_decode($s, true)` cannot tell `{}` from `[]`.** Both become an empty array, so \"an object with no\n  keys\" and \"a list with no items\" are the same value. Where the difference matters, decode that field\n  without the associative flag, or check the raw text first.\n- **A shallow `(array)` cast leaves nested objects in place.** The next level still holds objects, and the\n  array access on it fails later. Decode associatively, or convert recursively.\n- **A bare `(string)` cast turns an array into `\"Array\"`, and an `(int)` cast into 0 or 1.** `\"Array\"`\n  passes a non-empty check. Test `is_string` \u002F `is_int` first, then the keys, then use it.\n\n**Return the reason for the failure, not a boolean.** A caller that retries — a loop that feeds the error\nback to a model, a re-queued job — only improves when the feedback says which field was the wrong type.\n\n### Lenient parsing of config and `fromArray` inputs\n\n- **A default applies only when the key is absent.** Test with `array_key_exists`, never `??`: `??` treats\n  an explicit `null` as absent, so a cleared or mistyped value silently turns into the default. An explicit\n  `null` is invalid, and says so.\n- **Closed key sets are validated.** A map keyed by an enum, or a list of required cases, is checked for\n  unknown and for missing keys, and for being a list or a map as declared — an empty array is both.\n- **Env-derived scalars are parsed once**, by one parser that every reader calls. They arrive as strings:\n  `(bool) \"false\"` is true. Two readers parsing the same variable two ways is how a toggle is on in one\n  place and off in another.\n\n## 7b. Providers and the container\n\n- **A global bind or override does not reach a contextual binding of the same abstract.** A consumer with a\n  per-consumer binding keeps its own instance, so override both. Do it in `boot()`, after every\n  package's `register()` has run, or the package's own binding wins. The type hints are identical, the\n  wrong instance is injected, and nothing errors.\n- **A wrapper that carries one consumer's identity is inherited by the next consumer.** If a binding\n  decorates the implementation with a name, tenant or channel, every later consumer of that interface gets\n  the same decorated instance. Build the wrapper per consumer, or bind it contextually.\n- **`mergeConfigFrom()` merges one level deep, and the application's value wins.** A nested array the\n  application sets replaces the package's whole nested array, so the sibling defaults inside it disappear\n  without an error. When both the application's values and the package's nested defaults must survive,\n  merge that level explicitly instead of trusting the shallow merge.\n- **Check that an optional dependency is bound before resolving it, then let resolution fail loudly.** Ask\n  `bound()` first and resolve outside any `try`. Do not catch the container's binding-resolution exception\n  to mean \"not installed\": it is also thrown when a bound service has a constructor dependency that cannot\n  be resolved, and a `catch (Throwable)` swallows a missing extension on top of that. Either way the feature\n  quietly runs without a component that is installed but misconfigured.\n\n## 8. Code shape\n\nGuard clauses and early return; avoid `else` when a return makes the flow obvious. Small methods, one main\nresponsibility. Complex branches move into private methods or dedicated services. Comment decisions,\nconstraints and trade-offs — not the obvious.\n\n\nFour more, and the first one is the one people argue about:\n\n- **A variable holding a database field keeps the field's name.** Renaming it on the way in breaks the only\n  link between the row and the code, and makes the search that would have found every use return nothing.\n  Add a suffix when the variable means something narrower than the column, and keep the column's spelling\n  underneath it. Free naming is for values that are not a field.\n- **Display formatting has one home.** A presenter, a view model, a formatter — the name matters less than\n  the fact that there is exactly one, and that neither the model nor the template formats anything itself.\n  Otherwise the same value is rendered three ways in three screens and nobody can say which is right.\n- **Settings are a namespace, not a flat bag.** One root prefix, then area, then parameter; and a\n  convention in the name that says what kind of setting it is — a toggle reads as a toggle. A flat list of\n  a few hundred keys is a list nobody greps successfully.\n- **Directory and file naming is a convention, so it is one convention.** Two spellings in the same tree\n  means every path is a guess, and on a case-insensitive filesystem it also means it works locally and\n  fails on the server.\n\nAnti-patterns, in the order they appear: a 150-line method with several responsibilities; business logic\nmixed with I\u002FO or rendering; a boolean flag that changes what a method fundamentally does; names like `data`,\n`tmp`, `manager`, `utils` with no context.\n\n## 9. Files and storage\n\nStreams and chunks for large files, never the whole thing in memory. Validate type, size and destination\n**before** copying. No whole-export concatenation in RAM. Clean up temporary files and intermediate\nartefacts — including on the failure path, which is where they accumulate.\n\n---\n\n## 10. Failed jobs are a subsystem, not a table\n\nA job that exhausts its retries and lands in the failed table has failed **silently** unless something\nnotices. Give every job a common base that, on final failure, notifies — with the retry count and the\nbackoff as declared properties, and recipients and templates overridable per job for the ones that matter.\n\nThe question to answer for each job: **who finds out, and how long after?** If the answer is \"whoever\nhappens to look at the dashboard\", it is not a subsystem. See **`padosoft-failure-visibility`** and\n**`padosoft-durable-effects`**.\n\n## Gotchas\n\n- **`chunk` while updating skips rows.** Use `chunkById`.\n- **Mass updates bypass model events** (§6), and so do mass deletes and `upsert`.\n- **A `FormRequest` validating does not make `all()` safe**: it returns everything that was sent.\n- **Eager loading inside a loop is still N+1**, just harder to see.\n- **An index on a low-cardinality column often does nothing**; measure before adding.\n- **A job retried after a partial write repeats the write.** Idempotency is designed in, not hoped for.\n- **A global override does not reach a contextual binding** (§7b): the right type is injected, the wrong\n  instance behind it.\n- **`??` as the default for an optional key swallows an explicit `null`**, and a bare cast on decoded JSON\n  lets `\"Array\"` through (§7).\n- **`\u003C= $to` or `whereDate` on a date-only bound** loses the last day or the index (§4).\n- **`dd()` and `dump()` in committed code** — see `padosoft-logging-discipline` §3, and do not delete\n  someone else's silently: report it.\n\n## Checklist\n\n- [ ] Controller translates; logic in the service; DTO across boundaries\n- [ ] Job orchestrates, service implements; retryable vs permanent distinguished\n- [ ] No N+1; no `select *` on hot paths; bulk through `chunkById`\u002F`cursor` with filters in SQL\n- [ ] Soft-delete intent explicit in queries that care\n- [ ] Migration: responsibility, indexes on real patterns, nullability decided, source of truth documented\n- [ ] Bulk paths that bypass model events identified and handled\n- [ ] Full type hints; nullability resolved at the boundary\n- [ ] Decoded external data type- and shape-checked before use; date ranges half-open\n- [ ] Every config key, toggle and DTO field is read and honoured where it is bound; overrides cover contextual bindings\n- [ ] Pint and static analysis clean\n\n## Final report\n\n```\nChange: \u003Cwhat>  ·  Laravel \u003Cversion> \u002F PHP \u003Cversion>\nFlow: FormRequest \u003Cfile> → DTO \u003Cfile> → Service \u003Cfile> → Resource \u003Cfile>\nQueries: N+1 checked | bulk strategy \u003CchunkById|cursor|none needed>\nMigration: \u003Cyes\u002Fno — indexes, nullability, source of truth>\nModel events: bulk path \u003Cnot used | handled how>\nPint \u002F static analysis: PASS | FAIL \u003Cdetail>\n```\n",{"name":5,"license":14,"metadata":23,"description":7,"compatibility":31},{"scope":24,"author":25,"summary":26,"version":27,"keywords":28,"profiles":29,"repository":30},"project","Padosoft","Where the logic lives and what crosses which boundary, on any framework version.","0.5.0","laravel, php, eloquent, service, dto, job, queue, migration, n+1, architecture","laravel","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills","Any Laravel version. The rules are about how an application is shaped, not about framework features; where a version moved a file rather than changing a rule, the text says so.","main","8ff266762b08cab7f5be5551fa221309dc9db48b","skills\u002Fpadosoft-laravel-conventions",0,"https:\u002F\u002Fgithub.com\u002Fpadosoft","https:\u002F\u002Fwww.padosoft.com","Software House","2026-10-19 01:02:17",{"source":8,"skillName":5,"commands":41,"prompt":51,"zipAvailable":52},[42,45,48],{"tool":43,"command":44},"npx","npx skills add padosoft\u002Fskills --skill padosoft-laravel-conventions",{"tool":46,"command":47},"bunx","bunx skills add padosoft\u002Fskills --skill padosoft-laravel-conventions",{"tool":49,"command":50},"pnpm","pnpm dlx skills add padosoft\u002Fskills --skill padosoft-laravel-conventions","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpadosoft-laravel-conventions\u002FSKILL.md",true,[54],{"path":55,"resourceType":56,"resourceTypeDesc":57,"sizeBytes":58,"sourceHtmlUrl":59},"evals\u002Fqueries.json","REFERENCE","参考文档",1673,"https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Fskills\u002Fpadosoft-laravel-conventions\u002Fevals\u002Fqueries.json",[61,68,74,81,88,94],{"skillNo":62,"name":63,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":65,"categories":66,"keywords":67,"publishedAt":18},"01M7CZNKCTMWK7F2J6KKPAR8YM","report-opus","Writes the weekly status report from the team's tickets. Use when the user asks for the weekly report or a status summary. Do not use it for incident reports.","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Freport-opus\u002FSKILL.md",[],[],{"skillNo":69,"name":70,"nameZh":6,"description":64,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":71,"categories":72,"keywords":73,"publishedAt":18},"01M7CZNFEN8XK6S8NC6KGREYGS","report-haiku","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Freport-haiku\u002FSKILL.md",[],[],{"skillNo":75,"name":76,"nameZh":6,"description":77,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":78,"categories":79,"keywords":80,"publishedAt":18},"01M7CZND182TKGGM7R4134ND00","kitt-stub","Builds the guided-tour reference for an admin page. Use when the user asks for the tour reference. Trigger \"tour\", \"reference\", \"guided tour\".","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Fkitt-stub\u002FSKILL.md",[],[],{"skillNo":82,"name":83,"nameZh":6,"description":84,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":85,"categories":86,"keywords":87,"publishedAt":18},"01M7CZN9F2A6BFTFW5RSRNAGB1","good-skill","Generates the release notes of a project from its merged pull requests. Use this skill when the user asks for release notes, a changelog entry or a summary of what shipped since the last tag. Do not use it to write commit messages, that is the job of a commit skill.","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Fgood-skill\u002FSKILL.md",[],[],{"skillNo":89,"name":90,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":91,"categories":92,"keywords":93,"publishedAt":18},"01M7CZN6BJASPD4DH8DFR63GQF","broken-frontmatter","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Fbroken-frontmatter\u002FSKILL.md",[],[],{"skillNo":95,"name":96,"nameZh":6,"description":97,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":9,"repositoryNo":12,"starsCount":13,"licenseSpdxId":14,"licenseFileUrl":6,"sourceHtmlUrl":98,"categories":99,"keywords":100,"publishedAt":18},"01M7CZN498TRNC30GSYMMAZNXM","Bad_Skill","I can help you with reports.","https:\u002F\u002Fgithub.com\u002Fpadosoft\u002Fskills\u002Fblob\u002Fmain\u002Ftests\u002Ffixtures\u002Fskill-audit\u002Fproject\u002Fdot-claude\u002Fskills\u002Fbad-skill\u002FSKILL.md",[],[]]