{"id":"62c158a4-b2ec-42d7-a07a-5b86c2d48791","shortId":"2fPnvU","kind":"skill","title":"laravel-database-optimization","tagline":"Laravel database optimization patterns. Use when writing Eloquent queries, creating migrations, configuring caching, debugging slow queries, or optimizing database performance. Triggers on tasks involving N+1 queries, indexing, Redis caching, pagination, or database transactions.","description":"# Laravel Database Optimization\n\nComprehensive database optimization guide for Laravel 13 applications. Contains 33 rules across 9 categories for writing performant database queries, proper indexing, efficient caching, naming conventions, and debugging slow queries in Laravel 13.\n\n## Metadata\n\n- **Version:** 1.1.0\n- **Framework:** Laravel 13.x\n- **PHP:** 8.3+\n\n## When to Apply\n\nReference these guidelines when:\n- Writing Eloquent queries or using the query builder\n- Diagnosing and fixing N+1 query problems\n- Adding database indexes to migrations\n- Implementing Redis or cache-based optimizations\n- Paginating or processing large datasets\n- Wrapping operations in database transactions\n- Creating or modifying migrations for production databases\n- Debugging slow queries with EXPLAIN or Laravel Debugbar\n\n## Rule Categories by Priority\n\n| Priority | Category | Impact | Prefix |\n|----------|----------|--------|--------|\n| 1 | Query Performance & N+1 | CRITICAL | `query-` |\n| 2 | Indexing Strategies | CRITICAL | `index-` |\n| 3 | Eloquent Optimization | HIGH | `eloquent-` |\n| 4 | Caching with Redis | HIGH | `cache-` |\n| 5 | Pagination & Large Datasets | HIGH | `data-` |\n| 6 | Transactions & Locking | HIGH | `lock-` |\n| 7 | Migrations | HIGH | `migrate-` |\n| 8 | Query Debugging | MEDIUM | `debug-` |\n| 9 | Naming & Structure | HIGH | `naming-` |\n\n## Quick Reference\n\n### 1. Query Performance & N+1 (CRITICAL)\n\n- `query-eager-loading` - Use eager loading to eliminate N+1 queries\n- `query-prevent-lazy-loading` - Prevent lazy loading in development\n- `query-auto-eager-loading` - Configure automatic eager loading on models\n- `query-select-columns` - Select only needed columns instead of SELECT *\n\n### 2. Indexing Strategies (CRITICAL)\n\n- `index-foreign-keys` - Index all foreign key columns\n- `index-composite-indexes` - Create composite indexes for multi-column queries\n- `index-covering-indexes` - Use covering indexes for read-heavy queries\n- `index-full-text` - Use full-text indexes for search functionality\n\n### 3. Eloquent Optimization (HIGH)\n\n- `eloquent-query-builder-hot-paths` - Use query builder for performance-critical paths\n- `eloquent-with-count-aggregates` - Use withCount instead of loading relations to count\n- `eloquent-subquery-selects` - Use subquery selects to avoid extra queries\n- `eloquent-where-has-optimization` - Optimize whereHas with whereIn subqueries\n\n### 4. Caching with Redis (HIGH)\n\n- `cache-remember` - Use Cache::remember for expensive queries\n- `cache-invalidation` - Invalidate cache on model changes\n- `cache-tags` - Use cache tags for group invalidation\n- `cache-ttl` - Set appropriate TTL values for cached data\n\n### 5. Pagination & Large Datasets (HIGH)\n\n- `data-cursor-pagination` - Use cursor pagination for large datasets\n- `data-chunk-by-id` - Process large datasets with chunkById\n- `data-cursor-iteration` - Use lazy cursors for memory-efficient iteration\n- `data-avoid-unbounded` - Never use unbounded queries on large tables\n\n### 6. Transactions & Locking (HIGH)\n\n- `lock-short-transactions` - Keep transactions short and focused\n- `lock-deadlock-retry` - Implement deadlock retry logic\n- `lock-pessimistic-locking` - Use pessimistic locking for critical updates\n\n### 7. Migrations (HIGH)\n\n- `migrate-zero-downtime` - Write zero-downtime migrations\n- `migrate-concurrent-indexes` - Create indexes concurrently in production\n- `migrate-safe-column-additions` - Add columns safely without locking tables\n\n### 8. Query Debugging (MEDIUM)\n\n- `debug-explain-analyze` - Use EXPLAIN ANALYZE to understand query plans\n- `debug-laravel-debugbar` - Use Laravel Debugbar to find query bottlenecks\n- `debug-slow-query-log` - Enable and monitor slow query logs\n\n### 9. Naming & Structure (HIGH)\n\n- `naming-tables` - Table naming conventions (plural snake_case, pivot alphabetical)\n- `naming-columns` - Column naming conventions (FKs, booleans, timestamps, polymorphic)\n- `naming-relationships` - Relationship method naming (singular/plural matching)\n- `naming-migrations` - Migration and index naming conventions\n\n## Essential Patterns\n\n### Prevent Lazy Loading in Development\n\n```php\n<?php\n\nnamespace App\\Providers;\n\nuse Illuminate\\Database\\Eloquent\\Model;\nuse Illuminate\\Support\\ServiceProvider;\n\nclass AppServiceProvider extends ServiceProvider\n{\n    public function boot(): void\n    {\n        Model::preventLazyLoading(!app()->isProduction());\n    }\n}\n```\n\n### Cache Expensive Queries with Redis\n\n```php\n<?php\n\nuse Illuminate\\Support\\Facades\\Cache;\n\n// Cache a query result for 1 hour (3600 seconds)\n$popularPosts = Cache::remember('posts:popular', 3600, fn () =>\n    Post::query()\n        ->withCount('comments')\n        ->orderByDesc('comments_count')\n        ->take(10)\n        ->get()\n);\n```\n\n### Cursor Pagination for Large Datasets\n\n```php\n<?php\n\n// Cursor pagination — efficient for infinite scroll and large tables\n$posts = Post::query()\n    ->where('published_at', '<=', now())\n    ->orderByDesc('published_at')\n    ->cursorPaginate(15);\n```\n\n### Aggregate Counts Without Loading Relations\n\n```php\n<?php\n\n// Instead of loading all posts just to count them\n$users = User::withCount('posts')->get();\n\nforeach ($users as $user) {\n    echo \"{$user->name} has {$user->posts_count} posts\";\n}\n```\n\n### Process Large Datasets with chunkById\n\n```php\n<?php\n\n// Memory-efficient processing of large tables\nUser::query()\n    ->where('last_login_at', '<', now()->subYear())\n    ->chunkById(1000, function ($users) {\n        foreach ($users as $user) {\n            $user->update(['status' => 'inactive']);\n        }\n    });\n```\n\n### Short Database Transactions\n\n```php\n<?php\n\nuse Illuminate\\Support\\Facades\\DB;\n\n// Keep transactions short and focused\nDB::transaction(function () {\n    $order = Order::create([\n        'user_id' => auth()->id(),\n        'total' => $this->calculateTotal(),\n    ]);\n\n    $order->items()->createMany($this->cartItems());\n\n    $order->user->decrement('credits', $order->total);\n});\n```\n\n## How to Use\n\nRead individual rule files for detailed explanations and code examples:\n\n```\nrules/query-eager-loading.md\nrules/index-composite-indexes.md\nrules/cache-remember.md\nrules/_sections.md\n```\n\nEach rule file contains:\n- YAML frontmatter with metadata (title, impact, tags)\n- Brief explanation of why it matters\n- Bad Example with explanation\n- Good Example with explanation\n- Laravel 13 and PHP 8.3 specific context and references\n\n## References\n\n- [Laravel Eloquent](https://laravel.com/docs/13.x/eloquent)\n- [Laravel Queries](https://laravel.com/docs/13.x/queries)\n- [Laravel Cache](https://laravel.com/docs/13.x/cache)\n- [Laravel Pagination](https://laravel.com/docs/13.x/pagination)\n- [Laravel Migrations](https://laravel.com/docs/13.x/migrations)\n- [Laravel Redis](https://laravel.com/docs/13.x/redis)\n\n## Full Compiled Document\n\nFor the complete guide with all rules expanded: `AGENTS.md`","tags":["laravel","database","optimization","agent","skills","asyrafhussin","agent-rules","agent-skills","ai-agents","ai-slop","claude-code","code-quality"],"capabilities":["skill","source-asyrafhussin","skill-laravel-database-optimization","topic-agent-rules","topic-agent-skills","topic-ai-agents","topic-ai-slop","topic-claude-code","topic-code-quality","topic-code-review","topic-codex","topic-cursor","topic-laravel","topic-nodejs","topic-react"],"categories":["agent-skills"],"synonyms":[],"warnings":[],"endpointUrl":"https://skills.sh/AsyrafHussin/agent-skills/laravel-database-optimization","protocol":"skill","transport":"skills-sh","auth":{"type":"none","details":{"cli":"npx skills add AsyrafHussin/agent-skills","source_repo":"https://github.com/AsyrafHussin/agent-skills","install_from":"skills.sh"}},"qualityScore":"0.469","qualityRationale":"deterministic score 0.47 from registry signals: · indexed on github topic:agent-skills · 39 github stars · SKILL.md body (6,867 chars)","verified":false,"liveness":"unknown","lastLivenessCheck":null,"agentReviews":{"count":0,"score_avg":null,"cost_usd_avg":null,"success_rate":null,"latency_p50_ms":null,"narrative_summary":null,"summary_updated_at":null},"enrichmentModel":"deterministic:skill-github:v1","enrichmentVersion":1,"enrichedAt":"2026-05-18T18:58:24.536Z","embedding":null,"createdAt":"2026-05-16T18:57:14.276Z","updatedAt":"2026-05-18T18:58:24.536Z","lastSeenAt":"2026-05-18T18:58:24.536Z","tsv":"'+1':30,102,154,204,216 '/docs/13.x/cache)':852 '/docs/13.x/eloquent)':842 '/docs/13.x/migrations)':862 '/docs/13.x/pagination)':857 '/docs/13.x/queries)':847 '/docs/13.x/redis)':867 '1':150,200,631 '1.1.0':76 '10':650 '1000':736 '13':48,73,79,829 '15':679 '2':157,250 '3':162,299 '33':51 '3600':633,640 '4':167,351 '5':173,392 '6':179,440 '7':184,471 '8':188,503 '8.3':82,832 '9':54,193,540 'across':53 'ad':105 'add':497 'addit':496 'agents.md':879 'aggreg':321,680 'alphabet':554 'analyz':510,513 'app':591,612 'appli':85 'applic':49 'appropri':386 'appserviceprovid':603 'auth':770 'auto':230 'automat':234 'avoid':338,431 'bad':820 'base':115 'boolean':562 'boot':608 'bottleneck':528 'brief':814 'builder':97,306,311 'cach':17,34,64,114,168,172,352,357,360,366,369,374,377,383,390,614,625,626,636,849 'cache-bas':113 'cache-invalid':365 'cache-rememb':356 'cache-tag':373 'cache-ttl':382 'calculatetot':774 'cartitem':779 'case':552 'categori':55,143,147 'chang':372 'chunk':409 'chunkbyid':416,717,735 'class':602 'code':797 'column':242,246,262,273,495,498,557,558 'comment':645,647 'compil':869 'complet':873 'composit':265,268 'comprehens':42 'concurr':485,489 'configur':16,233 'contain':50,806 'context':834 'convent':66,549,560,580 'count':320,329,648,681,694,711 'cover':277,280 'creat':14,127,267,487,767 'createmani':777 'credit':783 'critic':155,160,205,253,315,469 'cursor':399,402,419,423,652,659 'cursorpagin':678 'data':178,391,398,408,418,430 'data-avoid-unbound':429 'data-chunk-by-id':407 'data-cursor-iter':417 'data-cursor-pagin':397 'databas':3,6,23,37,40,43,59,106,125,133,595,748 'dataset':121,176,395,406,414,656,715 'db':756,762 'deadlock':455,458 'debug':18,68,134,190,192,505,508,519,530 'debug-explain-analyz':507 'debug-laravel-debugbar':518 'debug-slow-query-log':529 'debugbar':141,521,524 'decrement':782 'detail':794 'develop':227,587 'diagnos':98 'document':870 'downtim':477,481 'eager':208,211,231,235 'echo':705 'effici':63,427,661,722 'elimin':214 'eloqu':12,91,163,166,300,304,318,331,342,596,839 'eloquent-query-builder-hot-path':303 'eloquent-subquery-select':330 'eloquent-where-has-optim':341 'eloquent-with-count-aggreg':317 'enabl':534 'essenti':581 'exampl':798,821,825 'expand':878 'expens':363,615 'explain':138,509,512 'explan':795,815,823,827 'extend':604 'extra':339 'facad':624,755 'file':792,805 'find':526 'fix':100 'fks':561 'fn':641 'focus':452,761 'foreach':701,739 'foreign':256,260 'framework':77 'frontmatt':808 'full':289,293,868 'full-text':292 'function':298,607,737,764 'get':651,700 'good':824 'group':380 'guid':45,874 'guidelin':88 'heavi':285 'high':165,171,177,182,186,196,302,355,396,443,473,543 'hot':307 'hour':632 'id':411,769,771 'illumin':594,599,622,753 'impact':148,812 'implement':110,457 'inact':746 'index':32,62,107,158,161,251,255,258,264,266,269,276,278,281,288,295,486,488,578 'index-composite-index':263 'index-covering-index':275 'index-foreign-key':254 'index-full-text':287 'individu':790 'infinit':663 'instead':247,324,687 'invalid':367,368,381 'involv':28 'isproduct':613 'item':776 'iter':420,428 'keep':448,757 'key':257,261 'laravel':2,5,39,47,72,78,140,520,523,828,838,843,848,853,858,863 'laravel-database-optim':1 'laravel.com':841,846,851,856,861,866 'laravel.com/docs/13.x/cache)':850 'laravel.com/docs/13.x/eloquent)':840 'laravel.com/docs/13.x/migrations)':860 'laravel.com/docs/13.x/pagination)':855 'laravel.com/docs/13.x/queries)':845 'laravel.com/docs/13.x/redis)':865 'larg':120,175,394,405,413,438,655,666,714,725 'last':730 'lazi':221,224,422,584 'load':209,212,222,225,232,236,326,585,683,689 'lock':181,183,442,445,454,462,464,467,501 'lock-deadlock-retri':453 'lock-pessimistic-lock':461 'lock-short-transact':444 'log':533,539 'logic':460 'login':731 'match':572 'matter':819 'medium':191,506 'memori':426,721 'memory-effici':425,720 'metadata':74,810 'method':569 'migrat':15,109,130,185,187,472,475,482,484,493,575,576,859 'migrate-concurrent-index':483 'migrate-safe-column-addit':492 'migrate-zero-downtim':474 'model':238,371,597,610 'modifi':129 'monitor':536 'multi':272 'multi-column':271 'n':29,101,153,203,215 'name':65,194,197,541,545,548,556,559,566,570,574,579,707 'namespac':590 'naming-column':555 'naming-migr':573 'naming-relationship':565 'naming-t':544 'need':245 'never':433 'oper':123 'optim':4,7,22,41,44,116,164,301,345,346 'order':765,766,775,780,784 'orderbydesc':646,675 'pagin':35,117,174,393,400,403,653,660,854 'path':308,316 'pattern':8,582 'perform':24,58,152,202,314 'performance-crit':313 'pessimist':463,466 'php':81,588,589,619,620,657,658,685,686,718,719,750,751,831 'pivot':553 'plan':517 'plural':550 'polymorph':564 'popular':639 'popularpost':635 'post':638,642,668,669,691,699,710,712 'prefix':149 'prevent':220,223,583 'preventlazyload':611 'prioriti':145,146 'problem':104 'process':119,412,713,723 'product':132,491 'proper':61 'provid':592 'public':606 'publish':672,676 'queri':13,20,31,60,70,92,96,103,136,151,156,189,201,207,217,219,229,240,274,286,305,310,340,364,436,504,516,527,532,538,616,628,643,670,728,844 'query-auto-eager-load':228 'query-eager-load':206 'query-prevent-lazy-load':218 'query-select-column':239 'quick':198 'read':284,789 'read-heavi':283 'redi':33,111,170,354,618,864 'refer':86,199,836,837 'relat':327,684 'relationship':567,568 'rememb':358,361,637 'result':629 'retri':456,459 'rule':52,142,791,804,877 'rules/_sections.md':802 'rules/cache-remember.md':801 'rules/index-composite-indexes.md':800 'rules/query-eager-loading.md':799 'safe':494,499 'scroll':664 'search':297 'second':634 'select':241,243,249,333,336 'serviceprovid':601,605 'set':385 'short':446,450,747,759 'singular/plural':571 'skill' 'skill-laravel-database-optimization' 'slow':19,69,135,531,537 'snake':551 'source-asyrafhussin' 'specif':833 'status':745 'strategi':159,252 'structur':195,542 'subqueri':332,335,350 'subyear':734 'support':600,623,754 'tabl':439,502,546,547,667,726 'tag':375,378,813 'take':649 'task':27 'text':290,294 'timestamp':563 'titl':811 'topic-agent-rules' 'topic-agent-skills' 'topic-ai-agents' 'topic-ai-slop' 'topic-claude-code' 'topic-code-quality' 'topic-code-review' 'topic-codex' 'topic-cursor' 'topic-laravel' 'topic-nodejs' 'topic-react' 'total':772,785 'transact':38,126,180,441,447,449,749,758,763 'trigger':25 'ttl':384,387 'unbound':432,435 'understand':515 'updat':470,744 'use':9,94,210,279,291,309,322,334,359,376,401,421,434,465,511,522,593,598,621,752,788 'user':696,697,702,704,706,709,727,738,740,742,743,768,781 'valu':388 'version':75 'void':609 'whereha':347 'wherein':349 'withcount':323,644,698 'without':500,682 'wrap':122 'write':11,57,90,478 'x':80 'yaml':807 'zero':476,480 'zero-downtim':479","prices":[{"id":"06b5c2b8-2d1b-42be-970f-7fb0a6936c14","listingId":"62c158a4-b2ec-42d7-a07a-5b86c2d48791","amountUsd":"0","unit":"free","nativeCurrency":null,"nativeAmount":null,"chain":null,"payTo":null,"paymentMethod":"skill-free","isPrimary":true,"details":{"org":"AsyrafHussin","category":"agent-skills","install_from":"skills.sh"},"createdAt":"2026-05-16T18:57:14.276Z"}],"sources":[{"listingId":"62c158a4-b2ec-42d7-a07a-5b86c2d48791","source":"github","sourceId":"AsyrafHussin/agent-skills/laravel-database-optimization","sourceUrl":"https://github.com/AsyrafHussin/agent-skills/tree/main/skills/laravel-database-optimization","isPrimary":false,"firstSeenAt":"2026-05-16T18:57:14.276Z","lastSeenAt":"2026-05-18T18:58:24.536Z"}],"details":{"listingId":"62c158a4-b2ec-42d7-a07a-5b86c2d48791","quickStartSnippet":null,"exampleRequest":null,"exampleResponse":null,"schema":null,"openapiUrl":null,"agentsTxtUrl":null,"citations":[],"useCases":[],"bestFor":[],"notFor":[],"kindDetails":{"org":"AsyrafHussin","slug":"laravel-database-optimization","github":{"repo":"AsyrafHussin/agent-skills","stars":39,"topics":["agent-rules","agent-skills","ai-agents","ai-slop","claude-code","code-quality","code-review","codex","cursor","laravel","nodejs","react","technical-debt","typescript","windsurf"],"license":"mit","html_url":"https://github.com/AsyrafHussin/agent-skills","pushed_at":"2026-05-16T19:24:02Z","description":"Agent skills for AI coding agents (Claude Code, Cursor, Codex, Windsurf) — Laravel, React, TypeScript, MySQL, code quality, technical debt, documentation, and security.","skill_md_sha":"03c1561e1614a806c7b152377d91490077fae47e","skill_md_path":"skills/laravel-database-optimization/SKILL.md","default_branch":"main","skill_tree_url":"https://github.com/AsyrafHussin/agent-skills/tree/main/skills/laravel-database-optimization"},"layout":"multi","source":"github","category":"agent-skills","frontmatter":{"name":"laravel-database-optimization","license":"MIT","description":"Laravel database optimization patterns. Use when writing Eloquent queries, creating migrations, configuring caching, debugging slow queries, or optimizing database performance. Triggers on tasks involving N+1 queries, indexing, Redis caching, pagination, or database transactions."},"skills_sh_url":"https://skills.sh/AsyrafHussin/agent-skills/laravel-database-optimization"},"updatedAt":"2026-05-18T18:58:24.536Z"}}