Communitygithub.com

patrones-laravel

Patrones de arquitectura Laravel, enrutamiento/controladores, Eloquent ORM, capas de servicio, colas, eventos, caché y recursos API para aplicaciones de producción. Útil al construir o revisar aplicaciones Laravel — controladores, Eloquent, capas de servicio, colas o recursos API.

¿Qué es patrones-laravel?

Este skill proporciona un conjunto completo de patrones de desarrollo Laravel orientados a producción, diseñados para construir aplicaciones escalables y mantenibles. Cubre desde la estructuración de proyectos (controladores, servicios, acciones, modelos), hasta el uso avanzado de Eloquent (relaciones, scopes, casts, eager loading), enrutamiento con vinculación de modelos, validación mediante Form Requests, recursos API con paginación, transacciones, colas, eventos y caché. Es ideal para desarrolladores que deseen estandarizar la arquitectura de sus proyectos Laravel, evitando errores comunes como consultas N+1, controladores 'gordos' o gestión deficiente de dependencias. Compatible con plataformas como Claude Code y asistentes similares, el skill ofrece ejemplos concretos de código y convenciones claras para capas como Actions, Services, Repositorios y Jobs. Su enfoque en separación de responsabilidades, tipado estricto y configuración explícita ayuda a mantener un código predecible y fácil de probar.

Compatible con~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/affaan-m/ECC/tree/main/skills/laravel-patterns

Preguntar en tu IA favorita

Abre un nuevo chat con esta habilidad de agente ya precargada.

Documentación

Patrones de Desarrollo Laravel

Patrones de arquitectura Laravel de grado de producción para aplicaciones escalables y mantenibles.

Cuándo Usarlo

  • Construir aplicaciones web o APIs con Laravel
  • Estructurar controladores, servicios y lógica de dominio
  • Trabajar con modelos y relaciones de Eloquent
  • Diseñar APIs con recursos y paginación
  • Añadir colas, eventos, caché y trabajos en segundo plano

Cómo Funciona

  • Estructurar la aplicación en torno a límites claros (controladores -> servicios/acciones -> modelos).
  • Usar vinculaciones explícitas y vinculaciones con ámbito para mantener el enrutamiento predecible; aún así, aplicar autorización para el control de acceso.
  • Favorecer modelos tipados, casts y scopes para mantener la lógica de dominio consistente.
  • Mantener el trabajo intensivo en IO en colas y cachear lecturas costosas.
  • Centralizar la configuración en config/* y mantener los entornos explícitos.

Ejemplos

Estructura del Proyecto

Usar una disposición convencional de Laravel con límites de capa claros (HTTP, servicios/acciones, modelos).

Disposición Recomendada

app/
├── Actions/            # Casos de uso de un solo propósito
├── Console/
├── Events/
├── Exceptions/
├── Http/
│   ├── Controllers/
│   ├── Middleware/
│   ├── Requests/       # Validación de Form Requests
│   └── Resources/      # Recursos API
├── Jobs/
├── Models/
├── Policies/
├── Providers/
├── Services/           # Servicios de coordinación de dominio
└── Support/
config/
database/
├── factories/
├── migrations/
└── seeders/
resources/
├── views/
└── lang/
routes/
├── api.php
├── web.php
└── console.php

Controladores -> Servicios -> Acciones

Mantener los controladores delgados. Poner la orquestación en servicios y la lógica de un solo propósito en acciones.

final class CreateOrderAction
{
    public function __construct(private OrderRepository $orders) {}

    public function handle(CreateOrderData $data): Order
    {
        return $this->orders->create($data);
    }
}

final class OrdersController extends Controller
{
    public function __construct(private CreateOrderAction $createOrder) {}

    public function store(StoreOrderRequest $request): JsonResponse
    {
        $order = $this->createOrder->handle($request->toDto());

        return response()->json([
            'success' => true,
            'data' => OrderResource::make($order),
            'error' => null,
            'meta' => null,
        ], 201);
    }
}

Enrutamiento y Controladores

Preferir la vinculación ruta-modelo y los controladores de recursos para mayor claridad.

use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->group(function () {
    Route::apiResource('projects', ProjectController::class);
});

Vinculación de Modelo de Ruta (Con Ámbito)

Usar vinculaciones con ámbito para prevenir el acceso entre inquilinos.

Route::scopeBindings()->group(function () {
    Route::get('/accounts/{account}/projects/{project}', [ProjectController::class, 'show']);
});

Rutas Anidadas y Nombres de Vinculación

  • Mantener prefijos y rutas consistentes para evitar doble anidamiento (ej., conversation vs conversations).
  • Usar un único nombre de parámetro que coincida con el modelo vinculado (ej., {conversation} para Conversation).
  • Preferir vinculaciones con ámbito al anidar para aplicar relaciones padre-hijo.
use App\Http\Controllers\Api\ConversationController;
use App\Http\Controllers\Api\MessageController;
use Illuminate\Support\Facades\Route;

Route::middleware('auth:sanctum')->prefix('conversations')->group(function () {
    Route::post('/', [ConversationController::class, 'store'])->name('conversations.store');

    Route::scopeBindings()->group(function () {
        Route::get('/{conversation}', [ConversationController::class, 'show'])
            ->name('conversations.show');

        Route::post('/{conversation}/messages', [MessageController::class, 'store'])
            ->name('conversation-messages.store');

        Route::get('/{conversation}/messages/{message}', [MessageController::class, 'show'])
            ->name('conversation-messages.show');
    });
});

Si deseas que un parámetro se resuelva a una clase de modelo diferente, define una vinculación explícita. Para lógica de vinculación personalizada, usa Route::bind() o implementa resolveRouteBinding() en el modelo.

use App\Models\AiConversation;
use Illuminate\Support\Facades\Route;

Route::model('conversation', AiConversation::class);

Vinculaciones del Contenedor de Servicios

Vincular interfaces a implementaciones en un proveedor de servicios para un cableado de dependencias claro.

use App\Repositories\EloquentOrderRepository;
use App\Repositories\OrderRepository;
use Illuminate\Support\ServiceProvider;

final class AppServiceProvider extends ServiceProvider
{
    public function register(): void
    {
        $this->app->bind(OrderRepository::class, EloquentOrderRepository::class);
    }
}

Patrones de Modelo Eloquent

Configuración del Modelo

final class Project extends Model
{
    use HasFactory;

    protected $fillable = ['name', 'owner_id', 'status'];

    protected $casts = [
        'status' => ProjectStatus::class,
        'archived_at' => 'datetime',
    ];

    public function owner(): BelongsTo
    {
        return $this->belongsTo(User::class, 'owner_id');
    }

    public function scopeActive(Builder $query): Builder
    {
        return $query->whereNull('archived_at');
    }
}

Casts Personalizados y Objetos de Valor

Usar enumeraciones u objetos de valor para un tipado estricto.

use Illuminate\Database\Eloquent\Casts\Attribute;

protected $casts = [
    'status' => ProjectStatus::class,
];
protected function budgetCents(): Attribute
{
    return Attribute::make(
        get: fn (int $value) => Money::fromCents($value),
        set: fn (Money $money) => $money->toCents(),
    );
}

Carga Anticipada para Evitar N+1

$orders = Order::query()
    ->with(['customer', 'items.product'])
    ->latest()
    ->paginate(25);

Objetos de Consulta para Filtros Complejos

final class ProjectQuery
{
    public function __construct(private Builder $query) {}

    public function ownedBy(int $userId): self
    {
        $query = clone $this->query;

        return new self($query->where('owner_id', $userId));
    }

    public function active(): self
    {
        $query = clone $this->query;

        return new self($query->whereNull('archived_at'));
    }

    public function builder(): Builder
    {
        return $this->query;
    }
}

Scopes Globales y Soft Deletes

Usar scopes globales para filtrado predeterminado y SoftDeletes para registros recuperables. Usar ya sea un scope global o un scope nombrado para el mismo filtro, no ambos, a menos que se desee un comportamiento en capas.

use Illuminate\Database\Eloquent\SoftDeletes;
use Illuminate\Database\Eloquent\Builder;

final class Project extends Model
{
    use SoftDeletes;

    protected static function booted(): void
    {
        static::addGlobalScope('active', function (Builder $builder): void {
            $builder->whereNull('archived_at');
        });
    }
}

Scopes de Consulta para Filtros Reutilizables

use Illuminate\Database\Eloquent\Builder;

final class Project extends Model
{
    public function scopeOwnedBy(Builder $query, int $userId): Builder
    {
        return $query->where('owner_id', $userId);
    }
}

// En servicio, repositorio, etc.
$projects = Project::ownedBy($user->id)->get();

Transacciones para Actualizaciones de Múltiples Pasos

use Illuminate\Support\Facades\DB;

DB::transaction(function (): void {
    $order->update(['status' => 'paid']);
    $order->items()->update(['paid_at' => now()]);
});

Migraciones

Convención de Nombres

  • Los nombres de archivo usan marcas de tiempo: YYYY_MM_DD_HHMMSS_create_users_table.php
  • Las migraciones usan clases anónimas (sin clase nombrada); el nombre del archivo comunica la intención
  • Los nombres de tabla están en snake_case y en plural por defecto

Ejemplo de Migración

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
    public function up(): void
    {
        Schema::create('orders', function (Blueprint $table): void {
            $table->id();
            $table->foreignId('customer_id')->constrained()->cascadeOnDelete();
            $table->string('status', 32)->index();
            $table->unsignedInteger('total_cents');
            $table->timestamps();
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('orders');
    }
};

Form Requests y Validación

Mantener la validación en form requests y transformar las entradas a DTOs.

use App\Models\Order;

final class StoreOrderRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('create', Order::class) ?? false;
    }

    public function rules(): array
    {
        return [
            'customer_id' => ['required', 'integer', 'exists:customers,id'],
            'items' => ['required', 'array', 'min:1'],
            'items.*.sku' => ['required', 'string'],
            'items.*.quantity' => ['required', 'integer', 'min:1'],
        ];
    }

    public function toDto(): CreateOrderData
    {
        return new CreateOrderData(
            customerId: (int) $this->validated('customer_id'),
            items: $this->validated('items'),
        );
    }
}

Recursos API

Mantener las respuestas API consistentes con recursos y paginación.

$projects = Project::query()->active()->paginate(25);

return response()->json([
    'success' => true,
    'data' => ProjectResource::collection($projects->items()),
    'error' => null,
    'meta' => [
        'page' => $projects->currentPage(),
        'per_page' => $projects->perPage(),
        'total' => $projects->total(),
    ],
]);

Eventos, Trabajos y Colas

  • Emitir eventos de dominio para efectos secundarios (correos electrónicos, analíticas)
  • Usar trabajos en cola para trabajo lento (informes, exportaciones, webhooks)
  • Preferir manejadores idempotentes con reintentos y retroceso

Caché

  • Cachear endpoints de lectura intensiva y consultas costosas
  • Invalidar cachés en eventos de modelo (created/updated/deleted)
  • Usar etiquetas al cachear datos relacionados para una invalidación fácil

Configuración y Entornos

  • Mantener secretos en .env y configuración en config/*.php
  • Usar anulaciones de configuración por entorno y config:cache en producción

Individual skills in this repo

This repo contains 20 individual skills — each has its own dedicated page.

accessibility

Design, implement, and audit inclusive digital products using WCAG 2.2 Level AA. Use when building or auditing UI that must meet WCAG 2.2 Level AA, or when reviewing a change for keyboard, contrast, or screen-reader support.

affaan-m/content-engine

Create platform-native content systems for X, LinkedIn, TikTok, YouTube, newsletters, and repurposed multi-platform campaigns. Use when the user wants social posts, threads, scripts, content calendars, or one source asset adapted cleanly across platforms.

affaan-m/ECC

Multi-platform content distribution across X, LinkedIn, Threads, and Bluesky. Adapts content per platform using content-engine patterns. Never posts identical content cross-platform. Use when the user wants to distribute content across social platforms.

affaan-m/fal-ai-media

Unified media generation via fal.ai MCP — image, video, and audio. Covers text-to-image (Nano Banana), text/image-to-video (Seedance, Kling, Veo 3), text-to-speech (CSM-1B), and video-to-audio (ThinkSound). Use when the user wants to generate images, videos, or audio with AI.

affaan-m/manim-video

日本語翻訳:このファイルは manim-video 用の日本語翻訳が必要です

affaan-m/remotion-video-creation

Remotion のベストプラクティス - React で動画を作成する。3D、アニメーション、音声、字幕、チャート、トランジションなどをカバーするドメイン固有の29のルール。

affaan-m/video-editing

AI-assisted video editing workflows for cutting, structuring, and augmenting real footage. Covers the full pipeline from raw capture through FFmpeg, Remotion, ElevenLabs, fal.ai, and final polish in Descript or CapCut. Use when the user wants to edit video, cut footage, create vlogs, or build video content.

agent-architecture-audit

Full-stack diagnostic for agent and LLM applications. Audits the 12-layer agent stack for wrapper regression, memory pollution, tool discipline failures, hidden repair loops, and rendering corruption. Produces severity-ranked findings with code-first fixes. Essential for developers building agent applications, autonomous loops, or any LLM-powered feature. Use when an agent or LLM feature misbehaves and the failing layer is unknown, or before shipping an agent stack.

agent-eval

Head-to-head comparison of coding agents (Claude Code, Aider, Codex, etc.) on custom tasks with pass rate, cost, time, and consistency metrics. Use when choosing between coding agents, or when a change to an agent setup needs measured pass rate, cost, and time rather than an impression.

agent-harness-construction

Design and optimize AI agent action spaces, tool definitions, and observation formatting for higher completion rates. Use when defining or revising an agent

agentic-engineering

Operate as an agentic engineer using eval-first execution, decomposition, and cost-aware model routing. Use when planning or executing engineering work that agents will carry out end to end.

agentic-os

Build persistent multi-agent operating systems on Claude Code. Covers kernel architecture, specialist agents, slash commands, file-based memory, scheduled automation, and state management without external databases. Use when building a persistent multi-agent system on Claude Code with its own memory, commands, and scheduling.

agent-introspection-debugging

Structured self-debugging workflow for AI agent failures using capture, diagnosis, contained recovery, and introspection reports. Use when an agent run fails and you need a reproducible diagnosis instead of a retry.

agent-payment-x402

Add x402 payment execution to AI agents with per-task budgets, spending controls, and non-custodial wallets. Supports Base through agentwallet-sdk and X Layer through OKX Payments / OKX Agent Payments Protocol. Use when an agent must pay for something itself and needs per-task budgets, spending controls, and a non-custodial wallet.

agent-self-evaluation

Use after completing any non-trivial task. The agent self-rates its output on 5 axes — accuracy, completeness, clarity, actionability, conciseness — with concrete evidence per criterion. Produces a structured 1-5 scorecard with specific improvement suggestions.

agent-sort

Build an evidence-backed ECC install plan for a specific repo by sorting skills, commands, rules, hooks, and extras into DAILY vs LIBRARY buckets using parallel repo-aware review passes. Use when ECC should be trimmed to what a project actually needs instead of loading the full bundle.

ai-first-engineering

Engineering operating model for teams where AI agents generate a large share of implementation output. Use when setting team process, review gates, or ownership rules for a codebase largely written by agents.

ai-regression-testing

Regression testing strategies for AI-assisted development. Sandbox-mode API testing without database dependencies, automated bug-check workflows, and patterns to catch AI blind spots where the same model writes and reviews code. Use when adding regression coverage to AI-assisted code, or when the same model both wrote and reviewed a change.

android-clean-architecture

Clean Architecture patterns for Android and Kotlin Multiplatform projects — module structure, dependency rules, UseCases, Repositories, and data layer patterns. Use when structuring modules, layers, or data flow in an Android or KMP project.

angular-developer

Generates Angular code and provides architectural guidance. Trigger when creating projects, components, or services, or for best practices on reactivity (signals, linkedSignal, resource), forms, dependency injection, routing, SSR, accessibility (ARIA), animations, styling (component styles, Tailwind CSS), testing, or CLI tooling.

Skills relacionados