Communitygithub.com

Laravelパターン

Laravelアプリケーションの構築・レビュー時に使用する、プロダクション向けアーキテクチャパターン集。ルーティング/コントローラ、Eloquent ORM、サービス層、キュー、イベント、キャッシュ、APIリソースをカバーします。

Laravelパターン とは?

このスキルは、Laravelアプリケーションをスケーラブルで保守しやすいものにするための、プロダクショングレードのアーキテクチャパターンを提供します。開発者は、コントローラ、Eloquentモデル、APIリソース、キュー、キャッシュなど、Laravel開発の主要な側面において、ベストプラクティスに沿った設計と実装を行うことができます。具体的には、コントローラを薄く保ち、サービス層やアクションクラスにビジネスロジックを委譲するレイヤードアーキテクチャ、ルートモデルバインディングやスコープバインディングを用いた明確なルーティング、型付きモデルやカスタムキャストによるドメインロジックの一貫性、N+1問題を回避するEager Loading、複雑なフィルタリングのためのクエリオブジェクト、フォームリクエストによるバリデーションとDTOへの変換、一貫性のあるAPIレスポンスを実現するAPIリソース、トランザクションやキューを活用した信頼性の高い処理、そして環境設定の管理方法をカバーしています。このスキルは、特にClaude Code、Cursor、CodexなどのAIエージェントがLaravelプロジェクトのコードを生成、レビュー、リファクタリングする際に役立ちます。Claude、GitHub Copilot、その他のAIアシスタントでも利用可能です。

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

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

Laravel開発パターン

スケーラブルで保守しやすいアプリケーションのための、プロダクショングレードのLaravelアーキテクチャパターン。

使用するタイミング

  • Laravel WebアプリケーションやAPIを構築するとき
  • コントローラ、サービス、ドメインロジックを構造化するとき
  • Eloquentモデルとリレーションを扱うとき
  • リソースとページネーションを使用したAPIを設計するとき
  • キュー、イベント、キャッシュ、バックグラウンドジョブを追加するとき

仕組み

  • 明確な境界(コントローラ -> サービス/アクション -> モデル)でアプリを構造化します。
  • 明示的なバインディングとスコープバインディングを使用してルーティングを予測可能にし、アクセス制御のために認可を実施します。
  • 型付きモデル、キャスト、スコープを優先してドメインロジックの一貫性を保ちます。
  • I/O負荷の高い作業はキューに任せ、高価な読み取りはキャッシュします。
  • 設定は config/* に集中させ、環境を明示的に保ちます。

例

プロジェクト構造

従来のLaravelレイアウトを使用し、明確なレイヤー境界(HTTP、サービス/アクション、モデル)を設けます。

推奨レイアウト

app/
├── Actions/            # 単一目的のユースケース
├── Console/
├── Events/
├── Exceptions/
├── Http/
│   ├── Controllers/
│   ├── Middleware/
│   ├── Requests/       # フォームリクエストバリデーション
│   └── Resources/      # APIリソース
├── Jobs/
├── Models/
├── Policies/
├── Providers/
├── Services/           # ドメインサービスを調整
└── Support/
config/
database/
├── factories/
├── migrations/
└── seeders/
resources/
├── views/
└── lang/
routes/
├── api.php
├── web.php
└── console.php

コントローラ -> サービス -> アクション

コントローラは薄く保ちます。オーケストレーションはサービスに、単一目的のロジックはアクションに配置します。

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);
    }
}

ルーティングとコントローラ

明確にするために、ルートモデルバインディングとリソースコントローラを優先します。

use Illuminate\Support\Facades\Route;

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

ルートモデルバインディング(スコープ)

クロステナントアクセスを防ぐために、スコープバインディングを使用します。

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

ネストされたルートとバインディング名

  • プレフィックスとパスを一貫させ、二重ネストを避けます(例:conversation vs conversations)。
  • バインドされたモデルと一致する単一のパラメータ名を使用します(例:{conversation} に Conversation)。
  • ネストする場合は、スコープバインディングを優先して親子関係を強制します。
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');
    });
});

パラメータを別のモデルクラスに解決したい場合は、明示的なバインディングを定義します。カスタムバインディングロジックには、Route::bind() を使用するか、モデルで resolveRouteBinding() を実装します。

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

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

サービスコンテナバインディング

明確な依存関係配線のために、サービスプロバイダでインターフェースを実装にバインドします。

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);
    }
}

Eloquentモデルパターン

モデル設定

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');
    }
}

カスタムキャストと値オブジェクト

厳格な型付けには、enumまたは値オブジェクトを使用します。

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(),
    );
}

N+1問題を回避するEager Loading

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

複雑なフィルタリングのためのクエリオブジェクト

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;
    }
}

グローバルスコープとソフトデリート

デフォルトのフィルタリングにはグローバルスコープを、復元可能なレコードには SoftDeletes を使用します。 同じフィルタにグローバルスコープと名前付きスコープの両方を、レイヤード動作を意図しない限り、使用しないでください。

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');
        });
    }
}

再利用可能なフィルタのためのクエリスコープ

use Illuminate\Database\Eloquent\Builder;

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

// サービス、リポジトリなどで
$projects = Project::ownedBy($user->id)->get();

複数ステップ更新のためのトランザクション

use Illuminate\Support\Facades\DB;

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

マイグレーション

命名規則

  • ファイル名にはタイムスタンプを使用します: YYYY_MM_DD_HHMMSS_create_users_table.php
  • マイグレーションは匿名クラスを使用します(名前付きクラスはなし)。ファイル名が意図を伝えます。
  • テーブル名は snake_case で、デフォルトで複数形です。

マイグレーションの例

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');
    }
};

フォームリクエストとバリデーション

バリデーションはフォームリクエストに記述し、入力をDTOに変換します。

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'),
        );
    }
}

APIリソース

リソースとページネーションを使用してAPIレスポンスを一貫させます。

$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(),
    ],
]);

イベント、ジョブ、キュー

  • 副作用(メール、分析)にはドメインイベントを発行します。
  • 低速な処理(レポート、エクスポート、Webhook)にはキュー投入ジョブを使用します。
  • リトライとバックオフを備えた冪等なハンドラを優先します。

キャッシュ

  • 読み取り負荷の高いエンドポイントと高価なクエリをキャッシュします。
  • モデルイベント(作成/更新/削除)でキャッシュを無効化します。
  • 関連データをキャッシュする場合はタグを使用して、簡単に無効化できるようにします。

設定と環境

  • シークレットは .env に、設定は config/*.php に保持します。
  • 環境ごとの設定オーバーライドを使用し、本番環境では config:cache を実行します。

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.

関連スキル