php-laravel

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Laravel Framework Skill

Laravel框架技能

Atomic skill for mastering Laravel application development
掌握Laravel应用开发的原子技能

Overview

概述

Comprehensive skill for building production-ready Laravel applications. Covers Laravel 10.x-11.x with focus on Eloquent ORM, Blade templating, API development, and queues.
全面掌握构建生产级Laravel应用的技能,涵盖Laravel 10.x-11.x版本,重点讲解Eloquent ORM、Blade模板、API开发和队列。

Skill Parameters

技能参数

Input Validation

输入验证

typescript
interface SkillParams {
  topic:
    | "eloquent"         // ORM, relationships, queries
    | "routing"          // Routes, middleware, controllers
    | "blade"            // Templates, components, layouts
    | "authentication"   // Sanctum, Passport, Fortify
    | "queues"           // Jobs, workers, Horizon
    | "testing"          // Feature tests, factories
    | "api";             // API resources, versioning

  level: "beginner" | "intermediate" | "advanced";
  laravel_version?: "10" | "11";
  stack?: "livewire" | "inertia-vue" | "inertia-react" | "blade-only";
}
typescript
interface SkillParams {
  topic:
    | "eloquent"         // ORM, 关联关系, 查询
    | "routing"          // 路由, 中间件, 控制器
    | "blade"            // 模板, 组件, 布局
    | "authentication"   // Sanctum, Passport, Fortify
    | "queues"           // 任务, 工作进程, Horizon
    | "testing"          // 功能测试, 工厂
    | "api";             // API资源, 版本控制

  level: "beginner" | "intermediate" | "advanced";
  laravel_version?: "10" | "11";
  stack?: "livewire" | "inertia-vue" | "inertia-react" | "blade-only";
}

Validation Rules

验证规则

yaml
validation:
  topic:
    required: true
    allowed: [eloquent, routing, blade, authentication, queues, testing, api]
  level:
    required: true
  laravel_version:
    default: "11"
yaml
validation:
  topic:
    required: true
    allowed: [eloquent, routing, blade, authentication, queues, testing, api]
  level:
    required: true
  laravel_version:
    default: "11"

Learning Modules

学习模块

Module 1: Eloquent ORM Mastery

模块1:Eloquent ORM精通

yaml
beginner:
  - Model basics and conventions
  - CRUD operations
  - Basic relationships

intermediate:
  - Advanced relationships (morphTo, hasManyThrough)
  - Eager loading and N+1 prevention
  - Query scopes

advanced:
  - Custom casts and accessors
  - Performance optimization
  - Database transactions

exercises:
  - Build blog with posts, comments, tags
  - Implement soft deletes
  - Create polymorphic media system
yaml
beginner:
  - 模型基础与约定
  - CRUD操作
  - 基础关联关系

intermediate:
  - 高级关联关系(morphTo, hasManyThrough)
  - 预加载与N+1查询问题解决
  - 查询作用域

advanced:
  - 自定义转换器与访问器
  - 性能优化
  - 数据库事务

exercises:
  - 构建包含文章、评论、标签的博客
  - 实现软删除
  - 创建多态媒体系统

Module 2: API Development

模块2:API开发

yaml
beginner:
  - API routes and controllers
  - JSON responses
  - Basic authentication (Sanctum)

intermediate:
  - API Resources and Collections
  - Pagination and filtering
  - Rate limiting

advanced:
  - OAuth with Passport
  - API versioning patterns
  - OpenAPI documentation
yaml
beginner:
  - API路由与控制器
  - JSON响应
  - 基础认证(Sanctum)

intermediate:
  - API资源与集合
  - 分页与过滤
  - 请求频率限制

advanced:
  - Passport实现OAuth
  - API版本控制模式
  - OpenAPI文档

Module 3: Queue Processing

模块3:队列处理

yaml
beginner:
  - Job basics and dispatching
  - Queue connections
  - Failed jobs handling

intermediate:
  - Job chaining and batching
  - Horizon monitoring

advanced:
  - Custom queue drivers
  - Saga patterns
yaml
beginner:
  - 任务基础与分发
  - 队列连接
  - 失败任务处理

intermediate:
  - 任务链式调用与批量处理
  - Horizon监控

advanced:
  - 自定义队列驱动
  - 传奇模式(Saga patterns)

Execution Flow

执行流程

mermaid
graph TD
    A[Skill Invoked] --> B{Validate Params}
    B -->|Invalid| C[Return Error]
    B -->|Valid| D{Check Laravel Version}
    D --> E[Load Version-Specific Content]
    E --> F{Topic Router}
    F --> G[Generate Examples + Exercises]
mermaid
graph TD
    A[技能调用] --> B{验证参数}
    B -->|无效| C[返回错误]
    B -->|有效| D{检查Laravel版本}
    D --> E[加载对应版本内容]
    E --> F{主题路由}
    F --> G[生成示例+练习]

Error Handling & Retry Logic

错误处理与重试逻辑

yaml
errors:
  VERSION_INCOMPATIBLE:
    code: "LARAVEL_001"
    recovery: "Suggest upgrade or alternative"

  PACKAGE_MISSING:
    code: "LARAVEL_002"
    recovery: "Provide composer require command"

retry:
  max_attempts: 3
  backoff:
    type: exponential
    initial_delay_ms: 100
yaml
errors:
  VERSION_INCOMPATIBLE:
    code: "LARAVEL_001"
    recovery: "建议升级或选择替代方案"

  PACKAGE_MISSING:
    code: "LARAVEL_002"
    recovery: "提供composer require命令"

retry:
  max_attempts: 3
  backoff:
    type: exponential
    initial_delay_ms: 100

Code Examples

代码示例

Eloquent Model (Laravel 11)

Eloquent模型(Laravel 11)

php
<?php
declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

final class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'slug', 'content', 'author_id'];

    protected function casts(): array
    {
        return [
            'published_at' => 'datetime',
        ];
    }

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

    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }

    public function scopePublished($query)
    {
        return $query->whereNotNull('published_at');
    }
}
php
<?php
declare(strict_types=1);

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

final class Post extends Model
{
    use HasFactory;

    protected $fillable = ['title', 'slug', 'content', 'author_id'];

    protected function casts(): array
    {
        return [
            'published_at' => 'datetime',
        ];
    }

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

    public function comments(): HasMany
    {
        return $this->hasMany(Comment::class);
    }

    public function scopePublished($query)
    {
        return $query->whereNotNull('published_at');
    }
}

API Resource Controller

API资源控制器

php
<?php
declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\PostResource;
use App\Models\Post;
use Illuminate\Http\Response;

final class PostController extends Controller
{
    public function index()
    {
        return PostResource::collection(
            Post::with(['author'])->paginate(15)
        );
    }

    public function store(StorePostRequest $request)
    {
        $post = Post::create($request->validated());

        return (new PostResource($post))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }
}
php
<?php
declare(strict_types=1);

namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\PostResource;
use App\Models\Post;
use Illuminate\Http\Response;

final class PostController extends Controller
{
    public function index()
    {
        return PostResource::collection(
            Post::with(['author'])->paginate(15)
        );
    }

    public function store(StorePostRequest $request)
    {
        $post = Post::create($request->validated());

        return (new PostResource($post))
            ->response()
            ->setStatusCode(Response::HTTP_CREATED);
    }
}

Queue Job

队列任务

php
<?php
declare(strict_types=1);

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;

final class SendWelcomeEmail implements ShouldQueue
{
    use Queueable, InteractsWithQueue;

    public int $tries = 3;
    public int $backoff = 60;

    public function __construct(
        public readonly User $user,
    ) {}

    public function middleware(): array
    {
        return [new WithoutOverlapping($this->user->id)];
    }

    public function handle(): void
    {
        $this->user->notify(new WelcomeNotification());
    }
}
php
<?php
declare(strict_types=1);

namespace App\Jobs;

use App\Models\User;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\Middleware\WithoutOverlapping;

final class SendWelcomeEmail implements ShouldQueue
{
    use Queueable, InteractsWithQueue;

    public int $tries = 3;
    public int $backoff = 60;

    public function __construct(
        public readonly User $user,
    ) {}

    public function middleware(): array
    {
        return [new WithoutOverlapping($this->user->id)];
    }

    public function handle(): void
    {
        $this->user->notify(new WelcomeNotification());
    }
}

Test Templates

测试模板

php
<?php
declare(strict_types=1);

namespace Tests\Feature\Api;

use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

final class PostApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_can_list_posts(): void
    {
        Post::factory()->count(5)->create();

        $this->getJson('/api/v1/posts')
            ->assertOk()
            ->assertJsonCount(5, 'data');
    }

    public function test_authenticated_user_can_create(): void
    {
        Sanctum::actingAs(User::factory()->create());

        $this->postJson('/api/v1/posts', ['title' => 'Test'])
            ->assertCreated();
    }
}
php
<?php
declare(strict_types=1);

namespace Tests\Feature\Api;

use App\Models\Post;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Laravel\Sanctum\Sanctum;
use Tests\TestCase;

final class PostApiTest extends TestCase
{
    use RefreshDatabase;

    public function test_can_list_posts(): void
    {
        Post::factory()->count(5)->create();

        $this->getJson('/api/v1/posts')
            ->assertOk()
            ->assertJsonCount(5, 'data');
    }

    public function test_authenticated_user_can_create(): void
    {
        Sanctum::actingAs(User::factory()->create());

        $this->postJson('/api/v1/posts', ['title' => 'Test'])
            ->assertCreated();
    }
}

Troubleshooting

故障排除

ProblemSolution
N+1 queriesUse
with()
for eager loading
Queue jobs stuckCheck QUEUE_CONNECTION, run
queue:work
Route not foundRun
route:clear
, check middleware
问题解决方案
N+1查询问题使用
with()
进行预加载
队列任务停滞检查QUEUE_CONNECTION配置,运行
queue:work
路由未找到运行
route:clear
,检查中间件配置

Quality Metrics

质量指标

MetricTarget
Code accuracy100%
Laravel conventions100%
N+1 prevention100%
指标目标值
代码准确性100%
遵循Laravel约定100%
解决N+1查询问题100%

Usage

使用方法

Skill("php-laravel", {topic: "eloquent", level: "intermediate"})
Skill("php-laravel", {topic: "eloquent", level: "intermediate"})