# Laravel Database Optimization

 

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.

 

**Licence** MIT

 

**Source** AsyrafHussin/agent-skills

 [Download zip](<https://delaparra-services.nl/skills/laravel-database-optimization/download>)   

# Laravel Database Optimization

 

Comprehensive 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.

 

## Metadata

 

- **Version:** 1.1.0 
- **Framework:** Laravel 13.x 
- **PHP:** 8.3+

 

## When to Apply

 

Reference these guidelines when:

 

- Writing Eloquent queries or using the query builder 
- Diagnosing and fixing N+1 query problems 
- Adding database indexes to migrations 
- Implementing Redis or cache-based optimizations 
- Paginating or processing large datasets 
- Wrapping operations in database transactions 
- Creating or modifying migrations for production databases 
- Debugging slow queries with EXPLAIN or Laravel Debugbar

 

## Rule Categories by Priority

    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- `    

## Quick Reference

 

### 1. Query Performance & N+1 (CRITICAL)

 

- ` query-eager-loading ` - Use eager loading to eliminate N+1 queries 
- ` query-prevent-lazy-loading ` - Prevent lazy loading in development 
- ` query-auto-eager-loading ` - Configure automatic eager loading on models 
- ` query-select-columns ` - Select only needed columns instead of SELECT \*

 

### 2. Indexing Strategies (CRITICAL)

 

- ` index-foreign-keys ` - Index all foreign key columns 
- ` index-composite-indexes ` - Create composite indexes for multi-column queries 
- ` index-covering-indexes ` - Use covering indexes for read-heavy queries 
- ` index-full-text ` - Use full-text indexes for search functionality

 

### 3. Eloquent Optimization (HIGH)

 

- ` eloquent-query-builder-hot-paths ` - Use query builder for performance-critical paths 
- ` eloquent-with-count-aggregates ` - Use withCount instead of loading relations to count 
- ` eloquent-subquery-selects ` - Use subquery selects to avoid extra queries 
- ` eloquent-where-has-optimization ` - Optimize whereHas with whereIn subqueries

 

### 4. Caching with Redis (HIGH)

 

- ` cache-remember ` - Use Cache::remember for expensive queries 
- ` cache-invalidation ` - Invalidate cache on model changes 
- ` cache-tags ` - Use cache tags for group invalidation 
- ` cache-ttl ` - Set appropriate TTL values for cached data

 

### 5. Pagination & Large Datasets (HIGH)

 

- ` data-cursor-pagination ` - Use cursor pagination for large datasets 
- ` data-chunk-by-id ` - Process large datasets with chunkById 
- ` data-cursor-iteration ` - Use lazy cursors for memory-efficient iteration 
- ` data-avoid-unbounded ` - Never use unbounded queries on large tables

 

### 6. Transactions & Locking (HIGH)

 

- ` lock-short-transactions ` - Keep transactions short and focused 
- ` lock-deadlock-retry ` - Implement deadlock retry logic 
- ` lock-pessimistic-locking ` - Use pessimistic locking for critical updates

 

### 7. Migrations (HIGH)

 

- ` migrate-zero-downtime ` - Write zero-downtime migrations 
- ` migrate-concurrent-indexes ` - Create indexes concurrently in production 
- ` migrate-safe-column-additions ` - Add columns safely without locking tables

 

### 8. Query Debugging (MEDIUM)

 

- ` debug-explain-analyze ` - Use EXPLAIN ANALYZE to understand query plans 
- ` debug-laravel-debugbar ` - Use Laravel Debugbar to find query bottlenecks 
- ` debug-slow-query-log ` - Enable and monitor slow query logs

 

### 9. Naming & Structure (HIGH)

 

- ` naming-tables ` - Table naming conventions (plural snake\_case, pivot alphabetical) 
- ` naming-columns ` - Column naming conventions (FKs, booleans, timestamps, polymorphic) 
- ` naming-relationships ` - Relationship method naming (singular/plural matching) 
- ` naming-migrations ` - Migration and index naming conventions

 

## Essential Patterns

 

### Prevent Lazy Loading in Development

 

```
<?php

namespace App\Providers;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\ServiceProvider;

class AppServiceProvider extends ServiceProvider
{
    public function boot(): void
    {
        Model::preventLazyLoading(!app()->isProduction());
    }
}
```

 

### Cache Expensive Queries with Redis

 

```
<?php

use Illuminate\Support\Facades\Cache;

// Cache a query result for 1 hour (3600 seconds)
$popularPosts = Cache::remember('posts:popular', 3600, fn () =>
    Post::query()
        ->withCount('comments')
        ->orderByDesc('comments_count')
        ->take(10)
        ->get()
);
```

 

### Cursor Pagination for Large Datasets

 

```
<?php

// Cursor pagination — efficient for infinite scroll and large tables
$posts = Post::query()
    ->where('published_at', '<=', now())
    ->orderByDesc('published_at')
    ->cursorPaginate(15);
```

 

### Aggregate Counts Without Loading Relations

 

```
<?php

// Instead of loading all posts just to count them
$users = User::withCount('posts')->get();

foreach ($users as $user) {
    echo "{$user->name} has {$user->posts_count} posts";
}
```

 

### Process Large Datasets with chunkById

 

```
<?php

// Memory-efficient processing of large tables
User::query()
    ->where('last_login_at', '<', now()->subYear())
    ->chunkById(1000, function ($users) {
        foreach ($users as $user) {
            $user->update(['status' => 'inactive']);
        }
    });
```

 

### Short Database Transactions

 

```
<?php

use Illuminate\Support\Facades\DB;

// Keep transactions short and focused
DB::transaction(function () {
    $order = Order::create([
        'user_id' => auth()->id(),
        'total' => $this->calculateTotal(),
    ]);

    $order->items()->createMany($this->cartItems());

    $order->user->decrement('credits', $order->total);
});
```

 

## How to Use

 

Read individual rule files for detailed explanations and code examples:

 

```
rules/query-eager-loading.md
rules/index-composite-indexes.md
rules/cache-remember.md
rules/_sections.md
```

 

Each rule file contains:

 

- YAML frontmatter with metadata (title, impact, tags) 
- Brief explanation of why it matters 
- Bad Example with explanation 
- Good Example with explanation 
- Laravel 13 and PHP 8.3 specific context and references

 

## References

 

- Laravel Eloquent 
- Laravel Queries 
- Laravel Cache 
- Laravel Pagination 
- Laravel Migrations 
- Laravel Redis

 

## Full Compiled Document

 

For the complete guide with all rules expanded: ` AGENTS.md `

 

## Files

 

- ` AGENTS.md ` 
- ` LICENSE ` 
- ` README.md ` 
- ` SKILL.md ` 
- ` SOURCE.md ` 
- ` metadata.json ` 
- ` rules/_sections.md ` 
- ` rules/_template.md ` 
- ` rules/cache-invalidation.md ` 
- ` rules/cache-remember.md ` 
- ` rules/cache-tags.md ` 
- ` rules/cache-ttl.md ` 
- ` rules/data-avoid-unbounded.md ` 
- ` rules/data-chunk-by-id.md ` 
- ` rules/data-cursor-iteration.md ` 
- ` rules/data-cursor-pagination.md ` 
- ` rules/debug-explain-analyze.md ` 
- ` rules/debug-laravel-debugbar.md ` 
- ` rules/debug-slow-query-log.md ` 
- ` rules/eloquent-query-builder-hot-paths.md ` 
- ` rules/eloquent-subquery-selects.md ` 
- ` rules/eloquent-where-has-optimization.md ` 
- ` rules/eloquent-with-count-aggregates.md ` 
- ` rules/index-composite-indexes.md ` 
- ` rules/index-covering-indexes.md ` 
- ` rules/index-foreign-keys.md ` 
- ` rules/index-full-text.md ` 
- ` rules/lock-deadlock-retry.md ` 
- ` rules/lock-pessimistic-locking.md ` 
- ` rules/lock-short-transactions.md ` 
- ` rules/migrate-concurrent-indexes.md ` 
- ` rules/migrate-safe-column-additions.md ` 
- ` rules/migrate-zero-downtime.md ` 
- ` rules/naming-columns.md ` 
- ` rules/naming-migrations.md ` 
- ` rules/naming-relationships.md ` 
- ` rules/naming-tables.md ` 
- ` rules/query-auto-eager-loading.md ` 
- ` rules/query-eager-loading.md ` 
- ` rules/query-prevent-lazy-loading.md ` 
- ` rules/query-select-columns.md `

 

## Related terms

 

- [ACID](<https://delaparra-services.nl/knowledge-hub/acid>) 
- [BEGIN / COMMIT / ROLLBACK](<https://delaparra-services.nl/knowledge-hub/begin-commit-rollback>) 
- [CASE](<https://delaparra-services.nl/knowledge-hub/case>) 
- [COALESCE](<https://delaparra-services.nl/knowledge-hub/coalesce>) 
- [COUNT / SUM / AVG / MIN / MAX](<https://delaparra-services.nl/knowledge-hub/count-sum-avg-min-max>) 
- [CROSS JOIN](<https://delaparra-services.nl/knowledge-hub/cross-join>) 
- [CTE (WITH)](<https://delaparra-services.nl/knowledge-hub/cte-with>) 
- [dirty read](<https://delaparra-services.nl/knowledge-hub/dirty-read>) 
- [DISTINCT](<https://delaparra-services.nl/knowledge-hub/distinct>) 
- [Document / NoSQL Database](<https://delaparra-services.nl/knowledge-hub/document-nosql-database>) 
- [EXISTS](<https://delaparra-services.nl/knowledge-hub/exists>) 
- [FULL OUTER JOIN](<https://delaparra-services.nl/knowledge-hub/full-outer-join>) 
- [Globally Distributed SQL](<https://delaparra-services.nl/knowledge-hub/globally-distributed-sql>) 
- [GROUP BY](<https://delaparra-services.nl/knowledge-hub/group-by>) 
- [HAVING](<https://delaparra-services.nl/knowledge-hub/having>) 
- [INNER JOIN](<https://delaparra-services.nl/knowledge-hub/inner-join>) 
- [LAG / LEAD](<https://delaparra-services.nl/knowledge-hub/lag-lead>) 
- [LEFT (OUTER) JOIN](<https://delaparra-services.nl/knowledge-hub/left-outer-join>) 
- [Managed Cache](<https://delaparra-services.nl/knowledge-hub/managed-cache>) 
- [Managed Database (SQL/Relational)](<https://delaparra-services.nl/knowledge-hub/managed-database-sqlrelational>) 
- [ORM (Object-Relational Mapper)](<https://delaparra-services.nl/knowledge-hub/orm-object-relational-mapper>) 
- [OVER](<https://delaparra-services.nl/knowledge-hub/over>) 
- [PARTITION BY](<https://delaparra-services.nl/knowledge-hub/partition-by>) 
- [phantom read](<https://delaparra-services.nl/knowledge-hub/phantom-read>) 
- [Query](<https://delaparra-services.nl/knowledge-hub/query>) 
- [RANK / DENSE\_RANK](<https://delaparra-services.nl/knowledge-hub/rank-dense-rank>) 
- [READ COMMITTED](<https://delaparra-services.nl/knowledge-hub/read-committed>) 
- [READ UNCOMMITTED](<https://delaparra-services.nl/knowledge-hub/read-uncommitted>) 
- [REPEATABLE READ](<https://delaparra-services.nl/knowledge-hub/repeatable-read>) 
- [RIGHT (OUTER) JOIN](<https://delaparra-services.nl/knowledge-hub/right-outer-join>) 
- [ROW\_NUMBER](<https://delaparra-services.nl/knowledge-hub/row-number>) 
- [running total](<https://delaparra-services.nl/knowledge-hub/running-total>) 
- [SELF JOIN](<https://delaparra-services.nl/knowledge-hub/self-join>) 
- [SERIALIZABLE](<https://delaparra-services.nl/knowledge-hub/serializable>) 
- [SQL (Structured Query Language)](<https://delaparra-services.nl/knowledge-hub/sql-structured-query-language>) 
- [subquery](<https://delaparra-services.nl/knowledge-hub/subquery>) 
- [Transaction](<https://delaparra-services.nl/knowledge-hub/transaction>) 
- [UNION vs UNION ALL](<https://delaparra-services.nl/knowledge-hub/union-vs-union-all>)

 

[Installing an agent skill in Claude Code, Codex, Cursor and Copilot](<https://delaparra-services.nl/manuals/een-skill-installeren-in-je-ai-assistent>)

[HTML version](https://delaparra-services.nl/skills/laravel-database-optimization)
