/filament-ai-skills:filament-query-auditfrom filament-ai-skills
Static analysis for Filament PHP files detecting N+1 queries, missing eager loads, cross-tenant data leaks, and missing indexes. Run before production via artisan command.
Ships in filament-ai-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
None: SKILL.md is the whole skill.
Auditoria estática de padrões de performance e segurança em arquivos Filament. Roda via php artisan filament:query-audit sem precisar de ambiente de produção ou tela lenta real.
Diferença vs query-performance-audit: esta skill é preventiva (análise de código), aquela é diagnóstica (tela lenta em runtime com EXPLAIN).
# Visão geral — quantos problemas por tipo
php artisan filament:query-audit --summary
# Erros críticos primeiro (crasha / vaza cross-tenant)
php artisan filament:query-audit --severity=error
# Tudo detalhado por arquivo
php artisan filament:query-audit
# Filtrar por resource/feature específica
php artisan filament:query-audit --filter=Order
php artisan filament:query-audit --filter=Product
# Saída JSON para processar programaticamente
php artisan filament:query-audit --json
| Severity | Significado | Ação |
|---|---|---|
error | N+1 concreto ou vazamento cross-tenant | Corrigir agora |
warn | Padrão suspeito, verificar contexto | Corrigir ou confirmar que está ok |
info | Oportunidade de melhoria | Corrigir quando conveniente |
Antes de corrigir, ler o arquivo apontado. O audit é estático — pode haver falsos positivos quando:
withoutGlobalScopes tem filtro tenant em método anteriorSelectFilter::relationship opera em model sem tenant_id (ex: Admin panel)missing-eager-load (warn)Sintoma: TextColumn::make('relation.column') sem ->with(['relation']) no mesmo arquivo.
// ❌ Problema — N+1: 1 query por linha para carregar 'person'
TextColumn::make('person.name')
// ✅ Fix em Table file — modifyQueryUsing
public static function configure(Table $table): Table
{
return $table
->modifyQueryUsing(fn (Builder $query) => $query->with(['person', 'vehicle']))
->columns([
TextColumn::make('person.name'),
TextColumn::make('vehicle.plate'),
]);
}
// ✅ Fix em Resource file — getEloquentQuery
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()->with(['person', 'vehicle']);
}
Se eager load já está no Resource e o check aponta no Table file — falso positivo, ignorar.
lazy-aggregate (error)Sintoma: $record->relation->count() ou ->sum() dentro de coluna ou state callback.
// ❌ Problema — carrega coleção inteira por linha
TextColumn::make('signers_total')
->state(fn (Envelope $record): int => $record->signers->count()),
// ✅ Fix — withCount na query + acesso ao atributo gerado
// No Table file ou Resource getEloquentQuery():
->modifyQueryUsing(fn (Builder $query) => $query->withCount('signers'))
// Na coluna:
TextColumn::make('signers_count') // Eloquent gera este atributo automaticamente
->label('Signatários')
->numeric(),
// Para sum/avg:
->modifyQueryUsing(fn ($query) => $query->withSum('items', 'total'))
// Acesso: $record->items_sum_total
Mapa de métodos:
| Lazy | Query | Atributo gerado |
|---|---|---|
->count() | withCount('rel') | rel_count |
->sum('col') | withSum('rel', 'col') | rel_sum_col |
->avg('col') | withAvg('rel', 'col') | rel_avg_col |
->min('col') | withMin('rel', 'col') | rel_min_col |
->max('col') | withMax('rel', 'col') | rel_max_col |
lazy-relation-in-state (warn)Sintoma: ->state(fn ($record) => $record->relation->property) — lazy load por linha.
// ❌ Problema
TextColumn::make('status_label')
->state(fn (Order $record): string => $record->person->name ?? '—'),
// ✅ Fix — eager load + acesso direto (ou usar dot notation)
->modifyQueryUsing(fn ($query) => $query->with(['person:id,name']))
// Ou melhor ainda, trocar para dot notation que Filament resolve internamente:
TextColumn::make('person.name')
->placeholder('—'),
without-global-scopes-no-tenant (error)Sintoma: ->withoutGlobalScopes() sem ->where('tenant_id', ...) no entorno.
// ❌ Problema — bypass do TenantScope expõe dados cross-tenant
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->withoutGlobalScopes([SoftDeletingScope::class]);
}
// ✅ Fix — filtrar tenant explicitamente após bypass
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()
->withoutGlobalScopes([SoftDeletingScope::class])
->where('tenant_id', Filament::getTenant()->id);
}
// ✅ Fix alternativo — bypassar só o scope de soft-delete, não o TenantScope
public static function getEloquentQuery(): Builder
{
return parent::getEloquentQuery()->withTrashed();
}
Verificar quais models do seu projeto possuem tenant scope global antes de corrigir.
select-filter-no-tenant-scope (warn)Sintoma: SelectFilter::relationship()->preload() sem modifyQueryUsing fora do Admin panel.
// ❌ Problema — preload carrega registros de todos tenants
SelectFilter::make('person')
->relationship('person', 'name')
->searchable()
->preload(),
// ✅ Fix — escopar ao tenant atual
SelectFilter::make('person')
->relationship('person', 'name', fn (Builder $query) => $query->where('tenant_id', Filament::getTenant()->id))
->searchable()
->preload(),
Pode ser falso positivo se o model da relação não tem
tenant_id(ex:User,Categoryglobal).
Verificar emdocs/SYSTEM.md §1se o model é multi-tenant antes de corrigir.
sortable-dotted-column (info)Sintoma: TextColumn::make('relation.column')->sortable() — Filament faz JOIN que pode fazer full scan.
// ❌ Problema — sort por relação sem índice no JOIN
TextColumn::make('person.name')->sortable(),
// Opção 1 — desabilitar sort na coluna
TextColumn::make('person.name')->searchable(), // sem ->sortable()
// Opção 2 — desnormalizar o valor no model (computed/stored)
// Migration: add column 'person_name' + trigger ou Observer para manter atualizado
// Opção 3 — garantir índice no campo relacionado
// Migration: $table->index('name') na tabela people
widget-get-no-eager-load (info)Sintoma: ->get() em widget sem ->with() precedente.
// ❌ Problema
protected function getStats(): array
{
$orders = Order::query()->where('status', 'in_progress')->get();
return $orders->map(fn ($order) => $order->person->name)->toArray(); // N+1
}
// ✅ Fix
protected function getStats(): array
{
$orders = Order::query()
->where('status', 'in_progress')
->with(['person:id,name'])
->get();
return $orders->map(fn ($order) => $order->person?->name)->toArray();
}
# 1. Rodar audit
php artisan filament:query-audit --summary
# 2. Focar em erros
php artisan filament:query-audit --severity=error
# 3. Para cada error: ler arquivo, aplicar fix, verificar
php artisan filament:query-audit --filter=NomeDoArquivo
# 4. Após fixes, re-rodar para confirmar redução
php artisan filament:query-audit --summary
# 5. Rodar testes dos resources afetados
php artisan test --compact --filter=ResourceTest
| Check | Cenário falso positivo | Como confirmar |
|---|---|---|
missing-eager-load | Eager load no Resource, check no Table file separado | Ler Resource file — se tem ->with(['rel']), ignorar |
without-global-scopes-no-tenant | Scope bypassed para incluir soft-deletes, tenant ok via outra rota | Ler ±20 linhas do contexto |
select-filter-no-tenant-scope | Model da relação não tem tenant_id | Checar docs/SYSTEM.md §1 |
sortable-dotted-column | Volume baixo, performance ok | Medir com EXPLAIN em produção se necessário |
pre-commit-review para validar o diffquery-performance-audit (EXPLAIN em runtime)DB::getQueryLog()What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
filament, laravel, n-plus-one, eager-loading, static-analysis, tenant-isolation
npx claudepluginhub felipearnold/filament-ai-skills --plugin filament-ai-skills18 skills in this plugin
/deep-code-reviewAnálise técnica profunda de código PHP/Laravel já implementado (não staged). 3 dimensões: segurança (OWASP), qualidade (SOLID, CC, DRY), padrões (PHP 8.4, Laravel 12, Filament v5). Foco em "como melhorar" — refactor, design, arquitetura. Gera relatório com scores e plano de ação. **Use pre-commit-review pra checklist rápido antes de commit.** Ativa: analisar implementação em profundidade, revisar feature pronta, audit de segurança, refatorar código existente, melhorar arquitetura, review profundo, análise completa, avaliar qualidade de feature, scoring de código./eloquent-query-checkVerifies and fixes direct static calls on Eloquent models, ensuring they always go through ::query() before methods like find, where, create, all, etc. Activate when: query(), Model::find, Model::create, Model::where, Model::all, eloquent query, static model call, model without query, fix model./error-detectiveOther plugins' skills for the same job