Fullstack PHP & Laravel
Trang chủ / Module 4
🌐 Module 4 / 19 · 4 ngày 📅 Tuần 3 ●○○○ Dễ

HTTP & REST API với Laravel: routing, Form Request, API Resource, lỗi chuẩn

Xây REST API đúng chuẩn bằng Laravel: route và controller gọn, validate bằng Form Request, định hình response bằng API Resource, phân trang cursor, xử lý lỗi nhất quán, versioning và tài liệu OpenAPI.

LaravelRESTForm RequestAPI ResourcePaginationError handling
📌 Vì sao module này quan trọng

Laravel giúp dựng API trong vài giờ — và cũng dễ tạo API tệ trong vài giờ: trả nguyên model (lộ cột nhạy cảm), validate rải rác trong controller, mỗi endpoint một định dạng lỗi. Nhà tuyển dụng nhìn status code, cấu trúc lỗi và cách tổ chức controller là biết bạn đã làm production hay chưa. Đây là module dễ nhưng là nền móng của capstone.

🎯 Mục tiêu học tập

  • Thiết kế resource REST, chọn đúng method và status code
  • Giữ controller mỏng; validate bằng Form Request, phân quyền bằng authorize()
  • Định hình response bằng API Resource, không bao giờ trả nguyên model
  • Phân trang offset và cursor; lọc, sắp xếp an toàn
  • Xử lý lỗi tập trung theo định dạng nhất quán, sinh tài liệu OpenAPI

Route, controller và cấu trúc

// routes/api.php
Route::prefix('v1')->middleware('auth:sanctum')->group(function () {
    Route::apiResource('projects', ProjectController::class);
    Route::apiResource('projects.tasks', TaskController::class)->shallow();
    Route::post('projects/{project}/archive', ArchiveProjectController::class);   // invokable cho hành động
});

// app/Http/Controllers/Api/V1/ProjectController.php
final class ProjectController
{
    public function store(StoreProjectRequest $request, CreateProject $action): ProjectResource
    {
        $project = $action->handle($request->user(), $request->validated());
        return ProjectResource::make($project);           // 201 tự động khi resource vừa được tạo
    }

    public function show(Project $project): ProjectResource   // route model binding
    {
        Gate::authorize('view', $project);
        return ProjectResource::make($project->load('owner'));
    }
}

Controller chỉ làm việc HTTP: nhận input đã validate, gọi một Action/Service, trả Resource. Logic nghiệp vụ nằm trong app/Actions hoặc domain (Module 5).

Form Request: validate và phân quyền tại biên

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

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:120'],
            'visibility' => ['required', Rule::enum(Visibility::class)],
            'due_date' => ['nullable', 'date', 'after:today'],
            'member_ids' => ['array', 'max:50'],
            'member_ids.*' => [Rule::exists('memberships', 'user_id')->where('organization_id', $this->user()->current_organization_id)],
        ];
    }
}
  • Chỉ dùng $request->validated() (hoặc safe()) — không bao giờ $request->all() vào create() (mass assignment, Module 8).
  • Lỗi validate tự trả 422 với errors theo từng field — frontend map thẳng vào form.
  • exists phải giới hạn theo tenant, nếu không người dùng gán được id của tổ chức khác.

API Resource: hợp đồng response

final class ProjectResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->public_id,
            'name' => $this->name,
            'status' => $this->status->value,
            'owner' => UserResource::make($this->whenLoaded('owner')),     // chỉ khi đã eager load → tránh N+1
            'tasks_count' => $this->whenCounted('tasks'),
            'can' => ['update' => $request->user()?->can('update', $this->resource)],
            'created_at' => $this->created_at->toIso8601String(),
        ];
    }
}

Resource là hợp đồng API tách khỏi schema DB: đổi tên cột không làm vỡ client, không lộ password, remember_token, cột nội bộ.

Phân trang, lọc, sắp xếp

public function index(Request $request): AnonymousResourceCollection
{
    $tasks = Task::query()
        ->whereBelongsTo($request->user()->currentOrganization)
        ->when($request->enum('status', TaskStatus::class), fn ($q, $s) => $q->where('status', $s))
        ->orderByDesc('created_at')->orderByDesc('id')          // sort ổn định
        ->with('assignee:id,name')
        ->cursorPaginate(perPage: min($request->integer('per_page', 20), 100));

    return TaskResource::collection($tasks);
}
  • paginate() (offset + COUNT) cho bảng admin; cursorPaginate() cho feed/danh sách lớn — nhanh ổn định ở trang sâu.
  • Cột sort lấy từ allowlist, không ghép thẳng input vào orderBy. Package spatie/laravel-query-builder chuẩn hoá filter/sort/include.
  • Giới hạn per_page tối đa.

Xử lý lỗi, versioning và tài liệu

// bootstrap/app.php (Laravel 11+)
->withExceptions(function (Exceptions $exceptions) {
    $exceptions->render(function (DomainException $e, Request $request) {
        if ($request->expectsJson()) {
            return response()->json([
                'type' => 'https://api.example.com/errors/domain',
                'title' => $e->getMessage(),
                'code' => class_basename($e),
                'request_id' => $request->header('X-Request-Id'),
            ], 422);
        }
    });
})
  • Chuẩn lỗi nhất quán (gợi ý RFC 9457 Problem Details), APP_DEBUG=false ở production — không bao giờ lộ stack trace.
  • 401 chưa đăng nhập, 403 không đủ quyền, 404 không tồn tại (hoặc thuộc tenant khác), 409 xung đột, 422 validate, 429 rate limit.
  • Versioning qua tiền tố /v1; thay đổi chỉ thêm field là tương thích ngược.
  • Tài liệu OpenAPI tự sinh: dedoc/scramble (đọc trực tiếp Form Request và Resource), hoặc Scribe.

🏋️ Bài tập thực hành

API quản lý Project/Task bản đầu tiên (nền móng capstone)

Tạo dự án Laravel mới (Sail hoặc Docker Compose). Xây REST API cho Organization → Project → Task: CRUD, gán người, đổi trạng thái theo enum, archive project. Yêu cầu: controller mỏng + Action class, Form Request cho mọi input, API Resource cho mọi output, cursor pagination, filter/sort qua allowlist, lỗi theo một định dạng, tài liệu OpenAPI bằng Scramble tại /docs/api, feature test Pest cho các status code 200/201/403/404/422. Tạm thời dùng token Sanctum đơn giản (Module 8 hoàn thiện auth).

📚 Tài nguyên học tập

✅ Tự đánh giá hoàn thành

  • Controller không chứa logic nghiệp vụ hay truy vấn phức tạp
  • Mọi input qua Form Request, mọi output qua API Resource
  • Dùng đúng status code và một định dạng lỗi
  • Có tài liệu OpenAPI và feature test