Chuyển đến nội dung
Skillpedia
Lập trình chung280k · #199

laravel-patterns

Skill này làm gì

Hướng dẫn này dạy cách tổ chức và cấu trúc dự án xây dựng bằng Laravel, một framework lập trình web. Nó chỉ cách làm code gọn gàng hơn, dễ hiểu hơn và dễ bảo trì, theo thực hành tốt nhất.

Khi nào nên dùng

  • ✓Khi bắt đầu một dự án Laravel mới.
  • ✓Khi xem lại hoặc cải thiện một dự án Laravel đang có.
  • ✓Khi làm việc với route, mô hình dữ liệu (Eloquent) hoặc logic nghiệp vụ.

Liên kết skill

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

Sao chép rồi dán vào AI của bạn (Claude, ChatGPT hoặc Cursor) và nhờ nó làm theo hướng dẫn.

Cách dùng

Cách dễ nhất: sao chép tin nhắn và dán vào AI của bạn. AI sẽ đọc skill và làm theo hướng dẫn.

Tin nhắn có sẵn để dán

Hãy dùng skill này để giúp tôi: https://github.com/affaan-m/ECC/blob/main/pi/core/skills/laravel-patterns/SKILL.md Đọc tệp SKILL.md tại liên kết đó và làm theo hướng dẫn cho việc của tôi.
Bạn muốn AI tự tìm những skill như thế này?Cài MCP Skillpedia miễn phí: chỉ một dòng, và AI sẽ tìm trong 15.000+ skill trước mỗi việc.Cài đặt trong 1 phút →

Ví dụ cách nhờ AI

“Làm sao để tổ chức code trong dự án Laravel tốt hơn để nó dễ mở rộng?”

5 skill mới mỗi tuần. Đọc chỉ 1 phút.

Cách hoạt động

Nó gợi ý tách các trách nhiệm thành các phần code khác nhau, như controller, service và model. Nó cũng hướng dẫn dùng các tính năng của Laravel như queue, event và cache để tối ưu hiệu năng.

Nội dung kỹ thuật (SKILL.md gốc)

Lấy nguyên văn từ GitHub, do tác giả viết bằng tiếng Anh.

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;


…
Câu hỏi thường gặp

'Mẫu kiến trúc' là gì?

Đây là các cách tổ chức code đã được kiểm chứng, giúp chương trình dễ hiểu, dễ bảo trì và dễ phát triển thêm.

Eloquent ORM là gì?

Đây là công cụ của Laravel giúp việc làm việc với cơ sở dữ liệu dễ hơn, cho phép bạn dùng code PHP để biểu diễn và thao tác dữ liệu thay vì viết SQL trực tiếp.

Tại sao nên chia code thành các 'tầng' (layer)?

Chia code thành các tầng (như giao diện, logic nghiệp vụ và truy cập dữ liệu) giúp phân công công việc rõ ràng và dễ sửa một phần mà không ảnh hưởng đến các phần khác.

Chi tiết

Mô tả gốc của tác giả

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

Độ phổ biến

Sao GitHub
280k
Vị trí xếp hạng
#199
Giấy phép
MIT
Cập nhật
15/10/2026

Skill này có hữu ích không?

0

Đăng nhập để bình chọn.

Bình luận

  • …

Thêm skill từ kho mã này

Skill tương tự