laravel-database-expert
Optimize Laravel queries with subqueries, joinSub, Redis cache-aside patterns, and read/write connection splitting. Use when writing complex joins, implementing Cache::remember with tags, or configuring database read replicas. (triggers: config/database.php, database/migrations/*.php, join, aggregate, subquery, selectRaw, Cache)
Best use case
laravel-database-expert is best used when you need a repeatable AI agent workflow instead of a one-off prompt.
Optimize Laravel queries with subqueries, joinSub, Redis cache-aside patterns, and read/write connection splitting. Use when writing complex joins, implementing Cache::remember with tags, or configuring database read replicas. (triggers: config/database.php, database/migrations/*.php, join, aggregate, subquery, selectRaw, Cache)
Teams using laravel-database-expert should expect a more consistent output, faster repeated execution, less prompt rewriting.
When to use this skill
- You want a reusable workflow that can be run more than once with consistent structure.
When not to use this skill
- You only need a quick one-off answer and do not need a reusable workflow.
- You cannot install or maintain the underlying files, dependencies, or repository context.
Installation
Claude Code / Cursor / Codex
Manual Installation
- Download SKILL.md from GitHub
- Place it in
.claude/skills/laravel-database-expert/SKILL.mdinside your project - Restart your AI agent — it will auto-discover the skill
How laravel-database-expert Compares
| Feature / Agent | laravel-database-expert | Standard Approach |
|---|---|---|
| Platform Support | Not specified | Limited / Varies |
| Context Awareness | High | Baseline |
| Installation Complexity | Unknown | N/A |
Frequently Asked Questions
What does this skill do?
Optimize Laravel queries with subqueries, joinSub, Redis cache-aside patterns, and read/write connection splitting. Use when writing complex joins, implementing Cache::remember with tags, or configuring database read replicas. (triggers: config/database.php, database/migrations/*.php, join, aggregate, subquery, selectRaw, Cache)
Where can I find the source code?
You can find the source code on GitHub using the link provided at the top of the page.
SKILL.md Source
# Laravel Database Expert
## **Priority: P1 (HIGH)**
## Workflow: Optimize a Slow Query
1. **Profile the query** — Use `DB::enableQueryLog()` or Laravel Debugbar.
2. **Add missing indexes** — Create a migration for join/where columns.
3. **Replace N+1** — Use `withCount()`, `withSum()`, or `addSelect` subqueries.
4. **Cache results** — Apply `Cache::remember()` with tags for frequently accessed data.
5. **Split reads/writes** — Configure `read`/`write` keys in `config/database.php`.
## Cache-Aside with Tags Example
See [implementation examples](references/implementation.md#cache-aside-with-tags) for cache-aside pattern with tag-based invalidation.
## Implementation Guidelines
### Advanced Query Builder
- **Complex Joins**: Prefer **`joinSub($subquery, 'alias', ...)`** and **`whereExists(fn($q) => $q->select(DB::raw(1))...)`** over raw SQL or `whereIn` for correlated subqueries.
- **Subqueries**: Use **`addSelect`** with a **`DB::raw`** subquery to avoid N+1 issues.
- **Aggregates**: Use **`withCount()`**, **`withSum()`**, and **`withAvg()`** directly via Eloquent for optimized column-based aggregation.
- **Raw Expressions**: Always use **`selectRaw`** or **`whereRaw`** with bindings; **never use string concatenation** in raw queries.
### Caching Strategy (Redis/Memcached)
- **Cache-Aside**: Utilize **`Cache::remember('key', $ttl, $closure)`** for frequently accessed data (e.g., `posts.all`).
- **Redis Tagging**: Group related keys using **`Cache::tags(['posts', 'user:1'])`** for **grouped invalidation**.
- **Invalidation**: Call **`Cache::tags(['posts'])->flush()`** to clear specific subsets; **never use `Cache::flush()` globally** in production.
### Scalability & Infrastructure
- **Read/Write Splitting**: Configure **'read'** and **'write'** keys in **`config/database.php`** mysql/pgsql connections. Laravel automatically routes **SELECT** to read and **INSERT/UPDATE/DELETE** to write; **no code changes needed**.
- **Indices**: Ensure correct **database indexes** are present on all join and aggregate columns.
## Anti-Patterns
- **No string SQL concatenation**: Use bindings or Query Builder.
- **No queries in loops**: Use subqueries, joins, or aggregates.
- **No `Cache::flush()`**: Use tags to target specific cache groups.
- **No direct Redis calls**: Use Laravel Cache wrappers consistently.
## References
- [Advanced SQL & Cache Patterns](references/implementation.md)Related Skills
nestjs-database
Implement data access patterns, Scaling, Migrations, and ORM selection in NestJS. Use when implementing TypeORM/Prisma repositories, migrations, or database patterns in NestJS. (triggers: **/*.entity.ts, prisma/schema.prisma, TypeOrmModule, PrismaService, MongooseModule, Repository)
laravel-tooling
Configure Laravel ecosystem with custom Artisan commands, Vite asset bundling, Pint code styling, and Horizon queue monitoring. Use when creating Artisan commands, migrating from Mix to Vite, or configuring Pint code standards. (triggers: package.json, composer.json, vite.config.js, artisan, vite, horizon, pint, blade)
laravel-testing
Write Pest feature tests with RefreshDatabase, mock external services, and create test data with Eloquent Factories in Laravel. Use when adding HTTP tests, configuring SQLite in-memory test database, or mocking payment services. (triggers: tests/**/*.php, phpunit.xml, feature, unit, mock, factory, sqlite)
laravel-sessions-middleware
Configure Redis session drivers, register security-header middleware, and prevent session fixation in Laravel. Use when switching session drivers, adding HSTS/CSP headers via middleware, or regenerating sessions after login. (triggers: app/Http/Middleware/**/*.php, config/session.php, session, driver, handle, headers, csrf)
laravel-security
Harden Laravel apps with Policies for model authorization, Gate-based RBAC, validated mass assignment, and CSRF protection. Use when creating authorization policies, securing env config access, or preventing mass assignment vulnerabilities. (triggers: app/Policies/**/*.php, config/*.php, policy, gate, authorize, env, config)
laravel-eloquent
Write performant Eloquent queries with eager loading, reusable scopes, and strict lazy-loading prevention in Laravel. Use when defining model relationships, creating query scopes, or processing large datasets with chunk/cursor. (triggers: app/Models/**/*.php, scope, with, eager, chunk, model)
laravel-clean-architecture
Implement Domain-Driven Design with typed DTOs, repository interfaces, and single-responsibility Action classes in Laravel. Use when creating domain folders, binding repository contracts in providers, or passing DTOs between layers. (triggers: app/Domains/**/*.php, app/Providers/*.php, domain, dto, repository, contract, adapter)
laravel-background-processing
Build scalable asynchronous workflows using Queues, Jobs, and Events in Laravel. Use when implementing queued jobs, event-driven workflows, or async processing in Laravel. (triggers: app/Jobs/**/*.php, app/Events/**/*.php, app/Listeners/**/*.php, ShouldQueue, dispatch, batch, chain, listener)
laravel-architecture
Enforce core architectural standards for scalable Laravel applications. Use when structuring controllers, service layers, action classes, Form Requests, or Service Container bindings in Laravel projects. (triggers: app/Http/Controllers/**/*.php, routes/*.php, controller, service, action, request, container)
laravel-api
Build REST endpoints with API Resources, Sanctum authentication, and versioned route groups in Laravel. Use when creating JsonResource classes, adding token-based auth, or defining rate-limited API routes. (triggers: routes/api.php, app/Http/Resources/**/*.php, resource, collection, sanctum, passport, cors)
golang-database
Implement database access with connection pooling and repository patterns in Go. Use when building database access, connection pools, or repositories in Go. (triggers: internal/adapter/repository/**, database, sql, postgres, gorm, sqlc, pgx)
database-redis
Optimize Redis caching, key management, and performance. Use when implementing Redis caching strategies, managing key namespaces, or optimizing Redis performance. (triggers: **/*.ts, **/*.js, **/redis.config.ts, redis, cache, ttl, eviction)