본문으로 건너뛰기
Skillpedia
일반 코딩280k · #199

laravel-patterns

하는 일

이 가이드는 웹 프로그래밍 프레임워크인 Laravel로 만든 프로젝트를 정리하는 방법을 알려 줍니다. 커뮤니티의 모범 사례에 따라 코드를 더 깔끔하고, 이해하기 쉽고, 유지보수하기 쉽게 만드는 방법을 보여 줍니다.

사용하는 경우

  • ✓새로운 Laravel 프로젝트를 시작할 때.
  • ✓기존 Laravel 프로젝트를 검토하고 개선할 때.
  • ✓라우트, 데이터 모델(Eloquent), 업무 로직을 다룰 때.

스킬 링크

https://github.com/affaan-m/ECC/blob/main/pi/core/skills/laravel-patterns/SKILL.md

복사해서 AI(Claude, ChatGPT, Cursor)에 붙여넣고 지침을 따르도록 요청하세요.

사용 방법

가장 쉬운 방법입니다. 메시지를 복사해 AI에 붙여넣으세요. AI가 스킬을 읽고 지침을 따릅니다.

바로 붙여넣을 수 있는 메시지

Use this skill to help me: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/laravel-patterns/SKILL.md Read the SKILL.md file at that link and follow its instructions for my task.
AI가 이런 스킬을 알아서 찾아 쓰길 원하시나요?무료 Skillpedia MCP를 설치하세요. 한 줄이면 작업마다 스킬 15,000+개 중에서 검색합니다.1분 만에 설치 →

AI에게 요청하는 예시

“Laravel 프로젝트에서 코드를 어떻게 더 잘 정리해야 확장하기 쉬울까요?”

매주 새 스킬 5개. 읽는 데 1분.

작동 방식

책임을 컨트롤러, 서비스, 모델 같은 여러 코드 부분으로 나누도록 제안합니다. 또한 큐, 이벤트, 캐싱 같은 Laravel 기능을 사용해 성능을 최적화하는 방법도 안내합니다.

기술 내용 (원본 SKILL.md)

작성자의 영어 원문을 GitHub에서 그대로 가져왔습니다.

Laravel Development Patterns

Production-grade Laravel architecture patterns for scalable, maintainable applications.

When to Use

  • Building Laravel web applications or APIs
  • Structuring controllers, services, and domain logic
  • Working with Eloquent models and relationships
  • Designing APIs with resources and pagination
  • Adding queues, events, caching, and background jobs

How It Works

  • Structure the app around clear boundaries (controllers -> services/actions -> models).
  • Use explicit bindings and scoped bindings to keep routing predictable; still enforce authorization for access control.
  • Favor typed models, casts, and scopes to keep domain logic consistent.
  • Keep IO-heavy work in queues and cache expensive reads.
  • Centralize config in config/* and keep environments explicit.

Examples

Project Structure

Use a conventional Laravel layout with clear layer boundaries (HTTP, services/actions, models).

Recommended Layout

app/
├── Actions/            # Single-purpose use cases
├── Console/
├── Events/
├── Exceptions/
├── Http/
│   ├── Controllers/
│   ├── Middleware/
│   ├── Requests/       # Form request validation
│   └── Resources/      # API resources
├── Jobs/
├── Models/
├── Policies/
├── Providers/
├── Services/           # Coordinating domain services
└── Support/
config/
database/
├── factories/
├── migrations/
└── seeders/
resources/
├── views/
└── lang/
routes/
├── api.php
├── web.php
└── console.php

Controllers -> Services -> Actions

Keep controllers thin. Put orchestration in services and single-purpose logic in actions.

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

Routing and Controllers

Prefer route-model binding and resource controllers for clarity.

use Illuminate\Support\Facades\Route;

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

Route Model Binding (Scoped)

Use scoped bindings to prevent cross-tenant access.

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

Nested Routes and Binding Names

  • Keep prefixes and paths consistent to avoid double nesting (e.g., conversation vs conversations).
  • Use a single parameter name that matches the bound model (e.g., {conversation} for Conversation).
  • Prefer scoped bindings when nesting to enforce parent-child relationships.
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');
    });
});

If you want a parameter to resolve to a different model class, define explicit binding. For custom binding logic, use Route::bind() or implement resolveRouteBinding() on the model.

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

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

Service Container Bindings

Bind interfaces to implementations in a service provider for clear dependency wiring.

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


…
자주 묻는 질문

‘아키텍처 패턴’이란 무엇인가요?

프로그램의 코드를 정리하는 검증된 방식입니다. 이해하기 쉽고, 유지보수하기 쉽고, 성장시키기 쉽게 만들어 줍니다.

Eloquent ORM이란 무엇인가요?

Laravel의 도구로, PHP 코드로 데이터를 표현하고 다룰 수 있게 해 주어 데이터베이스 작업을 쉽게 만듭니다. SQL을 직접 쓰지 않아도 됩니다.

코드를 ‘계층’으로 나누는 이유는 무엇인가요?

화면, 업무 로직, 데이터 접근처럼 계층별로 코드를 나누면 작업을 구분하기 쉽고, 한 부분을 수정해도 다른 부분에 영향을 덜 줍니다.

상세 정보

작성자의 원본 설명

Laravel architecture patterns, routing/controllers, Eloquent ORM, service layers, queues, events, caching, and API resources for production apps. Use when building or reviewing Laravel apps — controllers, Eloquent, service layers, queues, or API resources.

repo: affaan-m/ECC

인기도

GitHub 스타
280k
순위
#199
라이선스
MIT
업데이트
2026. 10. 15.

이 스킬이 유용한가요?

0

로그인 투표하려면 로그인하세요.

댓글

  • …

이 저장소의 다른 스킬

비슷한 스킬