{
    "url": "https://delaparra-services.nl/skills/laravel-database-optimization",
    "locale": "en",
    "title": "Laravel Database Optimization | DeLaParra Services",
    "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.",
    "alternates": {
        "en": "https://delaparra-services.nl/skills/laravel-database-optimization",
        "nl": "https://delaparra-services.nl/nl/skills/laravel-database-optimization"
    },
    "formats": {
        "csv": "https://delaparra-services.nl/skills/laravel-database-optimization.csv",
        "md": "https://delaparra-services.nl/skills/laravel-database-optimization.md",
        "json": "https://delaparra-services.nl/skills/laravel-database-optimization.json",
        "zip": "https://delaparra-services.nl/skills/laravel-database-optimization.zip",
        "pdf": "https://delaparra-services.nl/skills/laravel-database-optimization.pdf"
    },
    "downloads": [
        {
            "url": "https://delaparra-services.nl/skills/laravel-database-optimization.csv",
            "encodingFormat": "text/csv",
            "name": "laravel-database-optimization.csv"
        },
        {
            "url": "https://delaparra-services.nl/skills/laravel-database-optimization.json",
            "encodingFormat": "application/json",
            "name": "laravel-database-optimization.json"
        },
        {
            "url": "https://delaparra-services.nl/skills/laravel-database-optimization.md",
            "encodingFormat": "text/markdown",
            "name": "laravel-database-optimization.md"
        },
        {
            "url": "https://delaparra-services.nl/skills/laravel-database-optimization.pdf",
            "encodingFormat": "application/pdf",
            "name": "laravel-database-optimization.pdf"
        },
        {
            "url": "https://delaparra-services.nl/skills/laravel-database-optimization.zip",
            "encodingFormat": "application/zip",
            "name": "laravel-database-optimization.zip"
        },
        {
            "url": "https://delaparra-services.nl/skills/laravel-database-optimization/download",
            "encodingFormat": "application/zip",
            "name": "laravel-database-optimization-files.zip"
        }
    ],
    "markdown": "# Laravel Database Optimization\n\n \n\nLaravel 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.\n\n \n\n**Licence** MIT\n\n \n\n**Source** AsyrafHussin/agent-skills\n\n [Download zip](<https://delaparra-services.nl/skills/laravel-database-optimization/download>)   \n\n# Laravel Database Optimization\n\n \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 \n\n## Metadata\n\n \n\n- **Version:** 1.1.0 \n- **Framework:** Laravel 13.x \n- **PHP:** 8.3+\n\n \n\n## When to Apply\n\n \n\nReference these guidelines when:\n\n \n\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 \n\n## Rule Categories by Priority\n\n    Priority Category Impact Prefix     1 Query Performance & N+1 CRITICAL ` query- `   2 Indexing Strategies CRITICAL ` index- `   3 Eloquent Optimization HIGH ` eloquent- `   4 Caching with Redis HIGH ` cache- `   5 Pagination & Large Datasets HIGH ` data- `   6 Transactions & Locking HIGH ` lock- `   7 Migrations HIGH ` migrate- `   8 Query Debugging MEDIUM ` debug- `   9 Naming & Structure HIGH ` naming- `    \n\n## Quick Reference\n\n \n\n### 1. Query Performance & N+1 (CRITICAL)\n\n \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 \n\n### 2. Indexing Strategies (CRITICAL)\n\n \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 \n\n### 3. Eloquent Optimization (HIGH)\n\n \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 \n\n### 4. Caching with Redis (HIGH)\n\n \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 \n\n### 5. Pagination & Large Datasets (HIGH)\n\n \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 \n\n### 6. Transactions & Locking (HIGH)\n\n \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 \n\n### 7. Migrations (HIGH)\n\n \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 \n\n### 8. Query Debugging (MEDIUM)\n\n \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 \n\n### 9. Naming & Structure (HIGH)\n\n \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 \n\n## Essential Patterns\n\n \n\n### Prevent Lazy Loading in Development\n\n \n\n```\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 \n\n### Cache Expensive Queries with Redis\n\n \n\n```\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 \n\n### Cursor Pagination for Large Datasets\n\n \n\n```\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 \n\n### Aggregate Counts Without Loading Relations\n\n \n\n```\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 \n\n### Process Large Datasets with chunkById\n\n \n\n```\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 \n\n### Short Database Transactions\n\n \n\n```\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 \n\n## How to Use\n\n \n\nRead individual rule files for detailed explanations and code examples:\n\n \n\n```\nrules/query-eager-loading.md\nrules/index-composite-indexes.md\nrules/cache-remember.md\nrules/_sections.md\n```\n\n \n\nEach rule file contains:\n\n \n\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 \n\n## References\n\n \n\n- Laravel Eloquent \n- Laravel Queries \n- Laravel Cache \n- Laravel Pagination \n- Laravel Migrations \n- Laravel Redis\n\n \n\n## Full Compiled Document\n\n \n\nFor the complete guide with all rules expanded: ` AGENTS.md `\n\n \n\n## Files\n\n \n\n- ` AGENTS.md ` \n- ` LICENSE ` \n- ` README.md ` \n- ` SKILL.md ` \n- ` SOURCE.md ` \n- ` metadata.json ` \n- ` rules/_sections.md ` \n- ` rules/_template.md ` \n- ` rules/cache-invalidation.md ` \n- ` rules/cache-remember.md ` \n- ` rules/cache-tags.md ` \n- ` rules/cache-ttl.md ` \n- ` rules/data-avoid-unbounded.md ` \n- ` rules/data-chunk-by-id.md ` \n- ` rules/data-cursor-iteration.md ` \n- ` rules/data-cursor-pagination.md ` \n- ` rules/debug-explain-analyze.md ` \n- ` rules/debug-laravel-debugbar.md ` \n- ` rules/debug-slow-query-log.md ` \n- ` rules/eloquent-query-builder-hot-paths.md ` \n- ` rules/eloquent-subquery-selects.md ` \n- ` rules/eloquent-where-has-optimization.md ` \n- ` rules/eloquent-with-count-aggregates.md ` \n- ` rules/index-composite-indexes.md ` \n- ` rules/index-covering-indexes.md ` \n- ` rules/index-foreign-keys.md ` \n- ` rules/index-full-text.md ` \n- ` rules/lock-deadlock-retry.md ` \n- ` rules/lock-pessimistic-locking.md ` \n- ` rules/lock-short-transactions.md ` \n- ` rules/migrate-concurrent-indexes.md ` \n- ` rules/migrate-safe-column-additions.md ` \n- ` rules/migrate-zero-downtime.md ` \n- ` rules/naming-columns.md ` \n- ` rules/naming-migrations.md ` \n- ` rules/naming-relationships.md ` \n- ` rules/naming-tables.md ` \n- ` rules/query-auto-eager-loading.md ` \n- ` rules/query-eager-loading.md ` \n- ` rules/query-prevent-lazy-loading.md ` \n- ` rules/query-select-columns.md `\n\n \n\n## Related terms\n\n \n\n- [ACID](<https://delaparra-services.nl/knowledge-hub/acid>) \n- [BEGIN / COMMIT / ROLLBACK](<https://delaparra-services.nl/knowledge-hub/begin-commit-rollback>) \n- [CASE](<https://delaparra-services.nl/knowledge-hub/case>) \n- [COALESCE](<https://delaparra-services.nl/knowledge-hub/coalesce>) \n- [COUNT / SUM / AVG / MIN / MAX](<https://delaparra-services.nl/knowledge-hub/count-sum-avg-min-max>) \n- [CROSS JOIN](<https://delaparra-services.nl/knowledge-hub/cross-join>) \n- [CTE (WITH)](<https://delaparra-services.nl/knowledge-hub/cte-with>) \n- [dirty read](<https://delaparra-services.nl/knowledge-hub/dirty-read>) \n- [DISTINCT](<https://delaparra-services.nl/knowledge-hub/distinct>) \n- [Document / NoSQL Database](<https://delaparra-services.nl/knowledge-hub/document-nosql-database>) \n- [EXISTS](<https://delaparra-services.nl/knowledge-hub/exists>) \n- [FULL OUTER JOIN](<https://delaparra-services.nl/knowledge-hub/full-outer-join>) \n- [Globally Distributed SQL](<https://delaparra-services.nl/knowledge-hub/globally-distributed-sql>) \n- [GROUP BY](<https://delaparra-services.nl/knowledge-hub/group-by>) \n- [HAVING](<https://delaparra-services.nl/knowledge-hub/having>) \n- [INNER JOIN](<https://delaparra-services.nl/knowledge-hub/inner-join>) \n- [LAG / LEAD](<https://delaparra-services.nl/knowledge-hub/lag-lead>) \n- [LEFT (OUTER) JOIN](<https://delaparra-services.nl/knowledge-hub/left-outer-join>) \n- [Managed Cache](<https://delaparra-services.nl/knowledge-hub/managed-cache>) \n- [Managed Database (SQL/Relational)](<https://delaparra-services.nl/knowledge-hub/managed-database-sqlrelational>) \n- [ORM (Object-Relational Mapper)](<https://delaparra-services.nl/knowledge-hub/orm-object-relational-mapper>) \n- [OVER](<https://delaparra-services.nl/knowledge-hub/over>) \n- [PARTITION BY](<https://delaparra-services.nl/knowledge-hub/partition-by>) \n- [phantom read](<https://delaparra-services.nl/knowledge-hub/phantom-read>) \n- [Query](<https://delaparra-services.nl/knowledge-hub/query>) \n- [RANK / DENSE\\_RANK](<https://delaparra-services.nl/knowledge-hub/rank-dense-rank>) \n- [READ COMMITTED](<https://delaparra-services.nl/knowledge-hub/read-committed>) \n- [READ UNCOMMITTED](<https://delaparra-services.nl/knowledge-hub/read-uncommitted>) \n- [REPEATABLE READ](<https://delaparra-services.nl/knowledge-hub/repeatable-read>) \n- [RIGHT (OUTER) JOIN](<https://delaparra-services.nl/knowledge-hub/right-outer-join>) \n- [ROW\\_NUMBER](<https://delaparra-services.nl/knowledge-hub/row-number>) \n- [running total](<https://delaparra-services.nl/knowledge-hub/running-total>) \n- [SELF JOIN](<https://delaparra-services.nl/knowledge-hub/self-join>) \n- [SERIALIZABLE](<https://delaparra-services.nl/knowledge-hub/serializable>) \n- [SQL (Structured Query Language)](<https://delaparra-services.nl/knowledge-hub/sql-structured-query-language>) \n- [subquery](<https://delaparra-services.nl/knowledge-hub/subquery>) \n- [Transaction](<https://delaparra-services.nl/knowledge-hub/transaction>) \n- [UNION vs UNION ALL](<https://delaparra-services.nl/knowledge-hub/union-vs-union-all>)\n\n \n\n[Installing an agent skill in Claude Code, Codex, Cursor and Copilot](<https://delaparra-services.nl/manuals/een-skill-installeren-in-je-ai-assistent>)\n\n[HTML version](https://delaparra-services.nl/skills/laravel-database-optimization)\n",
    "structured_data": {
        "@context": "https://schema.org",
        "@graph": [
            {
                "@type": "Organization",
                "@id": "https://delaparra-services.nl/#practice",
                "logo": "https://delaparra-services.nl/logo.png",
                "name": "DeLaParra Services",
                "legalName": "DeLaParra Services",
                "url": "https://delaparra-services.nl/",
                "description": "Bespoke software, web applications and mobile apps, developed in Laravel by a single developer in Groningen. Fixed price agreed in advance, full source code provided upon delivery.",
                "email": "info@delaparra-services.nl",
                "address": {
                    "@type": "PostalAddress",
                    "addressLocality": "Groningen",
                    "addressRegion": "Groningen",
                    "addressCountry": "NL"
                },
                "areaServed": "Groningen, the Netherlands",
                "knowsLanguage": [
                    "en",
                    "nl"
                ],
                "knowsAbout": [
                    "Web design and development",
                    "App development",
                    "Custom software and web applications",
                    "OpenSpec",
                    "AI code review",
                    "Your own coding agent"
                ],
                "founder": {
                    "@id": "https://delaparra-services.nl/#person"
                }
            },
            {
                "@type": "WebPage",
                "@id": "https://delaparra-services.nl/skills/laravel-database-optimization#webpage",
                "url": "https://delaparra-services.nl/skills/laravel-database-optimization",
                "name": "Laravel Database Optimization | DeLaParra Services",
                "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.",
                "isPartOf": {
                    "@id": "https://delaparra-services.nl/#website"
                },
                "about": {
                    "@id": "https://delaparra-services.nl/#practice"
                },
                "inLanguage": "en",
                "breadcrumb": {
                    "@id": "https://delaparra-services.nl/skills/laravel-database-optimization#breadcrumb"
                }
            },
            {
                "@type": "BreadcrumbList",
                "@id": "https://delaparra-services.nl/skills/laravel-database-optimization#breadcrumb",
                "itemListElement": [
                    {
                        "@type": "ListItem",
                        "position": 1,
                        "name": "Home",
                        "item": "https://delaparra-services.nl/"
                    },
                    {
                        "@type": "ListItem",
                        "position": 2,
                        "name": "Laravel Database Optimization"
                    }
                ]
            },
            {
                "@type": "Person",
                "@id": "https://delaparra-services.nl/#person",
                "name": "Reinier de la Parra",
                "url": "https://delaparra-services.nl/about"
            },
            {
                "@type": "SoftwareSourceCode",
                "@id": "https://delaparra-services.nl/skills/laravel-database-optimization#skill",
                "url": "https://delaparra-services.nl/skills/laravel-database-optimization",
                "name": "Laravel Database Optimization",
                "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.",
                "inLanguage": "en",
                "license": "https://spdx.org/licenses/MIT.html",
                "subjectOf": {
                    "@id": "https://delaparra-services.nl/skills/laravel-database-optimization#dataset"
                }
            },
            {
                "@type": "Dataset",
                "@id": "https://delaparra-services.nl/skills/laravel-database-optimization#dataset",
                "name": "Laravel Database Optimization",
                "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.",
                "url": "https://delaparra-services.nl/skills/laravel-database-optimization",
                "identifier": "https://delaparra-services.nl/skills/laravel-database-optimization#dataset",
                "about": {
                    "@id": "https://delaparra-services.nl/skills/laravel-database-optimization#skill"
                },
                "creditText": "AsyrafHussin/agent-skills",
                "publisher": {
                    "@id": "https://delaparra-services.nl/#practice"
                },
                "license": "https://spdx.org/licenses/MIT.html",
                "isAccessibleForFree": true,
                "inLanguage": "en",
                "dateModified": "2026-11-28T14:00:11+00:00",
                "isPartOf": {
                    "@type": "Dataset",
                    "@id": "https://delaparra-services.nl/knowledge-hub#skills",
                    "name": "Skills for AI coding assistants",
                    "url": "https://delaparra-services.nl/knowledge-hub"
                },
                "includedInDataCatalog": {
                    "@type": "DataCatalog",
                    "@id": "https://delaparra-services.nl/knowledge-hub#catalog",
                    "name": "Knowledge hub data catalog",
                    "url": "https://delaparra-services.nl/knowledge-hub"
                },
                "distribution": [
                    {
                        "@type": "DataDownload",
                        "name": "laravel-database-optimization.csv",
                        "encodingFormat": "text/csv",
                        "contentUrl": "https://delaparra-services.nl/skills/laravel-database-optimization.csv",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:11+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "laravel-database-optimization.json",
                        "encodingFormat": "application/json",
                        "contentUrl": "https://delaparra-services.nl/skills/laravel-database-optimization.json",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:11+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "laravel-database-optimization.md",
                        "encodingFormat": "text/markdown",
                        "contentUrl": "https://delaparra-services.nl/skills/laravel-database-optimization.md",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:11+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "laravel-database-optimization.pdf",
                        "encodingFormat": "application/pdf",
                        "contentUrl": "https://delaparra-services.nl/skills/laravel-database-optimization.pdf",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:11+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "laravel-database-optimization.zip",
                        "encodingFormat": "application/zip",
                        "contentUrl": "https://delaparra-services.nl/skills/laravel-database-optimization.zip",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:11+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    },
                    {
                        "@type": "DataDownload",
                        "name": "laravel-database-optimization-files.zip",
                        "encodingFormat": "application/zip",
                        "contentUrl": "https://delaparra-services.nl/skills/laravel-database-optimization/download",
                        "inLanguage": "en",
                        "dateModified": "2026-11-28T14:00:11+00:00",
                        "license": "https://spdx.org/licenses/MIT.html"
                    }
                ]
            }
        ]
    }
}