Laravel database optimization

From AsyrafHussin/agent-skills · View interactive version

Laravel database optimization is an AI agent skill from the GitHub repository AsyrafHussin/agent-skills. 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.

How to use this skill

Skill file

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

When to Apply

Reference these guidelines when:

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)

2. Indexing Strategies (CRITICAL)

3. Eloquent Optimization (HIGH)

4. Caching with Redis (HIGH)

5. Pagination & Large Datasets (HIGH)

6. Transactions & Locking (HIGH)

7. Migrations (HIGH)

8. Query Debugging (MEDIUM)

9. Naming & Structure (HIGH)

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:

References

Full Compiled Document

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

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.