Laravel Database Optimization logo

Laravel Database Optimization

Community
AsyrafHussin
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.

Overview

PublisherAsyrafHussin
Repositoryagent-skills
Skill namelaravel-database-optimization
Stars
78
Forks
10
Bundled files
37
LicenseMIT
Links
  • Markdown instructions

    A SKILL.md file the model loads on demand, so it only costs tokens when a request actually matches.

  • Works with any LLM

    AI skills are plain Markdown, not provider-specific code, so this works with GPT, Claude, Gemini, Grok, or a local model.

  • 37 bundled files

    Scripts, templates, and references the model can read while it works. Files are read-only and never executed.

  • Open source

    Published by AsyrafHussin on GitHub. Read the source before you install it.

Installation

Install the Laravel Database Optimization AI skill in TypingMind to use it with any LLM, or drop it into another agent that reads SKILL.md.

1

Install in TypingMind

TypingMind installs a skill straight from its GitHub folder — it reads SKILL.md, bundles the resource files, and stores the result locally.

  1. Open the app and go to Plugins → Skills.
  2. Choose "Install from GitHub".
  3. Paste the skill folder URL below and confirm.
  4. Enable the skill in any chat where you want it available.
Plugins → Skills → Add skill → From GitHub URL, then paste the folder URL and press Continue.
2

Install in another agent

Any agent that reads the Agent Skills format can use this skill — copy the folder into that agent's skills directory.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/AsyrafHussin/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/laravel-database-optimization .claude/skills/laravel-database-optimization
Restart Claude Code after copying so it picks up the new skill.

Use it in TypingMind

Enable Laravel Database Optimization in any TypingMind chat and the model takes it from there. Its name and description sit in the system prompt, and the moment a request matches, the model loads the full instructions itself — you never invoke it by hand, and it costs no tokens until it is actually used.

The model loads Laravel Database Optimization on its own as soon as a request matches it.

Works with any AI model

AI skills are plain Markdown instructions rather than provider-specific code, so Laravel Database Optimization is not tied to the model it was written for. Install it once in TypingMind and use it with GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama, or a local model you run yourself — all on your own API keys.

  • Loaded only when it is needed

    The system prompt carries just the name and description. The instructions are fetched on the first matching request, so an idle skill costs nothing.

  • Switch models mid-chat

    Because the skill is instructions rather than code, changing model does not break it — the next model reads the same SKILL.md.

Skill instructions

This is the SKILL.md content the model loads. Read it before installing — a skill is instructions your model will follow.

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

PriorityCategoryImpactPrefix
1Query Performance & N+1CRITICALquery-
2Indexing StrategiesCRITICALindex-
3Eloquent OptimizationHIGHeloquent-
4Caching with RedisHIGHcache-
5Pagination & Large DatasetsHIGHdata-
6Transactions & LockingHIGHlock-
7MigrationsHIGHmigrate-
8Query DebuggingMEDIUMdebug-
9Naming & StructureHIGHnaming-

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

Full Compiled Document

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

Bundled files

The model reads these on demand while the skill is loaded. They are exposed as readable files and are never executed.

Frequently asked questions

What does the Laravel Database Optimization AI skill do?

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.

Why use Laravel Database Optimization on TypingMind?

Because you install it once and use it with any model. Laravel Database Optimization is plain Markdown rather than provider-specific code, so the same skill runs on GPT-5, Claude, Gemini, Grok, or a local model — and you can switch model mid-chat without it breaking. TypingMind runs on your own API keys, so you pay providers directly instead of a per-seat subscription, and your skills and chats stay in your own storage.

How do I install Laravel Database Optimization in TypingMind?

Open Plugins → Skills → Install from GitHub in TypingMind and paste https://github.com/AsyrafHussin/agent-skills/tree/main/skills/laravel-database-optimization. TypingMind reads its SKILL.md and bundles its files and installs it as a skill you can enable per chat.

Which AI models can use Laravel Database Optimization?

Any model you connect in TypingMind. AI skills are plain Markdown instructions rather than provider-specific code, so GPT, Claude, Gemini, Grok, and local models can all load this skill when a request matches it.

How many AI models can I use with Laravel Database Optimization?

As many as you like. As long as a model supports skills, you can use Laravel Database Optimization with it — GPT, Claude, Gemini, Grok, DeepSeek, Mistral, Llama and more — all on TypingMind with your own API keys.

Is the Laravel Database Optimization AI skill free?

Yes. It is published on GitHub by AsyrafHussin under the MIT license. You only pay your own AI provider for the tokens you use.

What are AI skills?

An AI skill is a reusable instruction bundle that teaches an AI model how to do one specific task. It follows the open Agent Skills format: a SKILL.md file with a name and description, plus any scripts, templates or reference files the model may need. The model reads the instructions only when your request matches the skill, so an installed skill costs nothing until it is used.

How are AI skills different from plugins or MCP servers?

A plugin or MCP server gives a model new tools to call — code that runs somewhere and returns a result. An AI skill gives the model knowledge and process instead: how to approach a task, which steps to follow, what good output looks like. Skills are plain Markdown, so they need no server, no API key and no runtime, and they work with any model.

View all

Set up your own AI workspace now

Get notified about new features and future giveaways by subscribing to our newsletter 👇