Php Laravel 标志

Php Laravel

社区
j4flmao
php-laravel

Use this skill when building Laravel applications — MVC structure, Eloquent ORM, service layer, validation, queues, and testing. This skill enforces: thin controllers, service layer for business logic, Eloquent best practices with eager loading, form request validation, and queue job structure. Requires Laravel 10+ or 11+. Do NOT use for: Symfony, WordPress, non-Laravel PHP frameworks.

概览

发布者j4flmao
代码仓库agent-skills
技能名称php-laravel
星标数
41
复刻数
6
附带文件
6
许可协议MIT
链接
  • Markdown 格式的指令

    模型按需加载 SKILL.md 文件,因此只有在请求确实与该技能匹配时才会消耗 Token。

  • 兼容任何大语言模型

    AI 技能采用纯 Markdown,而非特定提供商的代码,因此可搭配 GPT、Claude、Gemini、Grok 或本地模型使用。

  • 6 个附带文件

    模型执行任务时可读取的脚本、模板和参考资料。这些文件为只读文件,绝不会被执行。

  • 开源

    由 j4flmao 发布于 GitHub。请在安装前查看技能的源文件。

安装

在 TypingMind 中安装 Php Laravel AI 技能,即可搭配任意大语言模型使用;也可以将其放入其他支持读取 SKILL.md 的智能体中。

1

安装到 TypingMind

TypingMind 可直接从 GitHub 文件夹安装技能:读取 SKILL.md,打包资源文件,并将结果保存在本地。

  1. 打开应用,前往“插件 → 技能”。
  2. 选择“从 GitHub 安装”。
  3. 粘贴下方的技能文件夹 URL 并确认。
    https://github.com/j4flmao/agent-skills/tree/main/skills/backend/php/laravel
  4. 请在每个需要使用该技能的聊天中启用它。
依次选择“插件 → 技能 → 添加技能 → 从 GitHub URL 导入”,然后粘贴文件夹 URL 并点击“继续”。
2

安装到其他智能体

任何支持 Agent Skills 格式的智能体都可以使用此技能,只需将文件夹复制到该智能体的技能目录中。

Claude Code — .claude/skills
git clone --depth 1 https://github.com/j4flmao/agent-skills.git /tmp/agent-skills
mkdir -p .claude/skills
cp -r /tmp/agent-skills/skills/backend/php/laravel .claude/skills/php-laravel
复制后,请重启 Claude Code,以加载新技能。

在 TypingMind 中使用此技能

在任意 TypingMind 聊天中启用 Php Laravel,后续即可交由模型处理。技能的名称和描述会放在系统提示词中,一旦请求匹配,模型就会自动加载完整指令,无需您手动调用,且在实际使用前不会消耗 Token。

一旦请求与技能匹配,模型就会自动加载 Php Laravel。

兼容任何 AI 模型

AI 技能是纯 Markdown 指令,而非特定提供商的代码,因此 Php Laravel 不局限于最初适配的模型。只需在 TypingMind 中安装一次,即可搭配 GPT-5、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 或您自行运行的本地模型使用,全程使用您自己的 API 密钥。

  • 仅在需要时加载

    系统提示词中仅包含技能名称和描述。首次遇到匹配的请求时才会加载完整指令,因此技能未使用时,这些指令不会消耗 Token。

  • 在聊天中切换模型

    技能是指令而非代码,因此切换模型不会导致技能失效,新模型会读取同一个 SKILL.md。

技能指令

这是模型会加载的 SKILL.md 内容。请在安装前阅读,因为技能就是模型将遵循的指令。

Laravel

Purpose

Build Laravel applications with clean MVC structure, service layer separation, Eloquent ORM best practices, form request validation, queue jobs, and comprehensive testing.

Agent Protocol

Trigger

User request includes: Laravel structure, Laravel app, Eloquent, Laravel service, Laravel validation, Laravel queue, Laravel testing, Laravel job, Laravel seeder.

Input Context

  • Laravel version (10.x, 11.x)
  • PHP version (8.1+)
  • Database (MySQL, PostgreSQL, SQLite)
  • Features (Auth, Queues, Broadcasting, Notifications, Cashier)

Output Artifact

Controller structure, service class, Eloquent model, form request, job class, seeder, test.

Response Format

Produce artifact directly. No preamble, no postamble, no explanations.

Completion Criteria

  • Controller delegates to service layer
  • Eloquent model with scopes, relations, casts
  • Form request class with validation rules
  • Service class with business logic
  • Queue job with typed properties
  • Feature/unit tests for critical paths

Max Response Length

4096 tokens

Architecture Decision Trees

Service Layer vs Repository vs Active Record

CriterionService LayerRepositoryActive Record (Vanilla)
Business logic locationService classRepository classModel methods
Query abstractionService delegates to modelRepository encapsulatesDirect in controllers
TestabilityEasy (mock service)Moderate (mock repo)Hard (Eloquent facade)
ComplexityModerateHigh (extra layer)Low
Laravel fitNatural (dedicated directories)Possible but uncommonDefault pattern

Decision: Business logic outside controllers → Service Layer (most common in production Laravel apps). Need query abstraction → Repository. Simple CRUD → Active Record in controllers is acceptable.

Form Request vs Controller Validation

CriterionForm RequestController validate()Manual validation
ReusabilityAcross controllers/actionsPer methodPer method
AuthorizationBuilt-in authorize()Manual in controllerManual
NamingStoreUserRequestInline arrayInline array
Logic complexityCustom rules, after hooksSimple rulesSimple rules

Decision: Reusable validation → Form Request. Simple one-off → Controller validate(). Complex custom logic → Form Request with custom rules.

Workflow

Step 1: Directory Structure

app/
  Http/
    Controllers/
      Api/
        V1/
          UserController.php
          OrderController.php
    Requests/
      StoreUserRequest.php
      UpdateUserRequest.php
    Resources/
      UserResource.php
  Models/
    User.php
    Order.php
  Services/
    UserService.php
    OrderService.php
  Jobs/
    ProcessOrderJob.php
  Exceptions/
    ConflictException.php
database/
  migrations/
    xxxx_create_users_table.php
  factories/
    UserFactory.php
  seeders/
    UserSeeder.php
routes/
  api.php
tests/
  Feature/
    UserTest.php
  Unit/
    UserServiceTest.php

Step 2: Eloquent Model

php
<?php
// app/Models/User.php
namespace App\Models;

use Illuminate\Database\Eloquent\Concerns\HasUuids;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Foundation\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;

class User extends Authenticatable
{
    use HasFactory, HasUuids, Notifiable;

    protected $fillable = [
        'name', 'email', 'password', 'role', 'is_active',
    ];

    protected $hidden = ['password', 'remember_token'];

    protected function casts(): array
    {
        return [
            'email_verified_at' => 'datetime',
            'password' => 'hashed',
            'is_active' => 'boolean',
            'created_at' => 'datetime:Y-m-d\TH:i:s\Z',
        ];
    }

    // Scopes
    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function scopeByRole($query, string $role)
    {
        return $query->where('role', $role);
    }

    // Relations
    public function posts(): HasMany
    {
        return $this->hasMany(Post::class);
    }

    // Accessors
    public function getInitialsAttribute(): string
    {
        $parts = explode(' ', $this->name);
        return collect($parts)->map(fn($p) => strtoupper($p[0]))->implode('');
    }

    // Events
    protected static function booted(): void
    {
        static::created(function ($user) {
            event(new UserCreated($user));
        });
    }
}

Step 3: Form Request Validation

php
<?php
// app/Http/Requests/StoreUserRequest.php
namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;

class StoreUserRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()?->can('create-users') ?? false;
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'min:2', 'max:255'],
            'email' => ['required', 'email', Rule::unique('users')],
            'password' => ['required', 'string', 'min:8'],
            'role' => ['sometimes', Rule::in(['admin', 'user', 'moderator'])],
        ];
    }

    public function messages(): array
    {
        return [
            'email.unique' => 'This email is already registered.',
        ];
    }

    protected function prepareForValidation(): void
    {
        $this->merge([
            'email' => strtolower($this->email),
        ]);
    }
}

Step 4: Service Layer

php
<?php
// app/Services/UserService.php
namespace App\Services;

use App\Exceptions\ConflictException;
use App\Models\User;
use Illuminate\Support\Facades\Hash;
use Illuminate\Support\Facades\DB;
use Illuminate\Pagination\LengthAwarePaginator;

class UserService
{
    public function __construct(
        private readonly NotificationService $notifications,
    ) {}

    public function create(array $data): User
    {
        if (User::where('email', $data['email'])->exists()) {
            throw new ConflictException('Email already exists');
        }

        return DB::transaction(function () use ($data) {
            $user = User::create([
                'name' => $data['name'],
                'email' => $data['email'],
                'password' => Hash::make($data['password']),
                'role' => $data['role'] ?? 'user',
            ]);

            $this->notifications->sendWelcomeEmail($user);

            return $user;
        });
    }

    public function findById(string $id): ?User
    {
        return User::with('posts')->find($id);
    }

    public function paginate(int $perPage = 20): LengthAwarePaginator
    {
        return User::active()
            ->withCount('posts')
            ->orderBy('created_at', 'desc')
            ->paginate($perPage);
    }

    public function update(string $id, array $data): User
    {
        $user = User::findOrFail($id);
        $user->update($data);
        return $user->fresh();
    }

    public function delete(string $id): void
    {
        User::findOrFail($id)->delete();
    }
}

Step 5: API Resource (DTO)

php
<?php
// app/Http/Resources/UserResource.php
namespace App\Http\Resources;

use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;

class UserResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'role' => $this->role,
            'is_active' => $this->is_active,
            'posts_count' => $this->whenCounted('posts'),
            'created_at' => $this->created_at,
        ];
    }
}

Step 6: Thin Controller

php
<?php
// app/Http/Controllers/Api/V1/UserController.php
namespace App\Http\Controllers\Api\V1;

use App\Http\Controllers\Controller;
use App\Http\Requests\StoreUserRequest;
use App\Http\Requests\UpdateUserRequest;
use App\Http\Resources\UserResource;
use App\Services\UserService;
use Illuminate\Http\JsonResponse;

class UserController extends Controller
{
    public function __construct(
        private readonly UserService $userService,
    ) {}

    public function index(): JsonResponse
    {
        $users = $this->userService->paginate();
        return response()->json([
            'data' => UserResource::collection($users),
            'meta' => [
                'current_page' => $users->currentPage(),
                'last_page' => $users->lastPage(),
                'total' => $users->total(),
            ],
        ]);
    }

    public function store(StoreUserRequest $request): JsonResponse
    {
        $user = $this->userService->create($request->validated());
        return response()->json([
            'data' => new UserResource($user),
        ], 201);
    }

    public function show(string $id): JsonResponse
    {
        $user = $this->userService->findById($id);
        abort_if(!$user, 404, 'User not found');
        return response()->json(['data' => new UserResource($user)]);
    }

    public function update(UpdateUserRequest $request, string $id): JsonResponse
    {
        $user = $this->userService->update($id, $request->validated());
        return response()->json(['data' => new UserResource($user)]);
    }

    public function destroy(string $id): JsonResponse
    {
        $this->userService->delete($id);
        return response()->json(null, 204);
    }
}

Step 7: Queue Job

php
<?php
// app/Jobs/ProcessOrderJob.php
namespace App\Jobs;

use App\Models\Order;
use App\Services\InventoryService;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;

class ProcessOrderJob implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

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

    public function __construct(
        private readonly Order $order,
    ) {}

    public function handle(InventoryService $inventory): void
    {
        try {
            $inventory->reserveItems($this->order);
            $this->order->markAsProcessing();
        } catch (InsufficientInventoryException $e) {
            $this->order->markAsFailed($e->getMessage());
            $this->fail($e);
        }
    }

    public function failed(\Throwable $e): void
    {
        $this->order->markAsFailed($e->getMessage());
        event(new OrderFailed($this->order));
    }
}

Step 8: Exception Handler

php
<?php
// app/Exceptions/Handler.php
namespace App\Exceptions;

use Illuminate\Foundation\Exceptions\Handler as ExceptionHandler;
use Illuminate\Validation\ValidationException;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
use Symfony\Component\HttpKernel\Exception\HttpException;

class Handler extends ExceptionHandler
{
    public function render($request, \Throwable $e)
    {
        if ($request->expectsJson()) {
            return match (true) {
                $e instanceof ConflictException => response()->json([
                    'error' => ['code' => 'CONFLICT', 'message' => $e->getMessage()],
                ], 409),
                $e instanceof ValidationException => response()->json([
                    'error' => ['code' => 'VALIDATION_ERROR', 'details' => $e->errors()],
                ], 422),
                $e instanceof NotFoundHttpException => response()->json([
                    'error' => ['code' => 'NOT_FOUND', 'message' => 'Resource not found'],
                ], 404),
                $e instanceof HttpException => response()->json([
                    'error' => ['code' => 'ERROR', 'message' => $e->getMessage()],
                ], $e->getStatusCode()),
                default => response()->json([
                    'error' => ['code' => 'INTERNAL_ERROR', 'message' => 'An error occurred'],
                ], 500),
            };
        }

        return parent::render($request, $e);
    }
}

Implementation Patterns

Pattern: Caching with Cache Tags

php
public function findWithCache(string $id): ?User
{
    return Cache::tags(['users'])->remember("user.{$id}", 3600, function () use ($id) {
        return User::with('posts')->find($id);
    });
}

public function invalidateUserCache(string $id): void
{
    Cache::tags(['users'])->forget("user.{$id}");
}

Production Considerations

Eloquent Performance

  • Always use with() or load() to eager load — never lazy load in Blade
  • Use cursor() or chunk() for large datasets, never all()
  • Add indexes in migrations for all foreign keys and frequently queried columns
  • Use select to limit columns: User::select(['id', 'name', 'email'])
  • Avoid N+1: install Laravel Debugbar or Telescope in development to detect

Horizon/Queue Configuration

php
// config/horizon.php — production queue management
'environments' => [
    'production' => [
        'supervisor-1' => [
            'connection' => 'redis',
            'queue' => ['high', 'default', 'low'],
            'balance' => 'auto',
            'processes' => 3,
            'tries' => 3,
        ],
    ],
],

Anti-Patterns

Anti-PatternWhyFix
Business logic in controllerUntestable, violates SRPDelegate to service class
Global active() scope on UserHidden filterExplicit scopes in queries
N+1 queries in Blade100+ SQL queries per pageEager load with with()
all() on large tablesMemory exhaustionUse cursor(), chunk(), or paginate
Events/Signals for non-decoupled concernsHard to trace flowUse listeners for side effects
dd()/dump() in committed codeBreaks API responsesUse logger instead

Security Considerations

  • Hash::make() for passwords — never plain text or MD5/SHA
  • Form Request authorize() for permission checks
  • $guarded or $fillable on all models — never unguarded
  • CSRF protection enabled by default — never disable on state-changing routes
  • Rate limiting via RateLimiter facade or throttle middleware
  • SQL injection: Eloquent is safe (parameterized), but DB::raw() can be vulnerable
  • XSS: {{ }} Blade syntax auto-escapes; {!! !!} only for trusted HTML

Testing Strategies

php
// tests/Feature/UserControllerTest.php
class UserControllerTest extends TestCase
{
    use RefreshDatabase;

    public function test_can_create_user(): void
    {
        $response = $this->postJson('/api/v1/users', [
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'password' => 'password123',
        ]);

        $response->assertStatus(201)
            ->assertJsonStructure(['data' => ['id', 'name', 'email']]);
    }

    public function test_duplicate_email_returns_conflict(): void
    {
        User::factory()->create(['email' => 'john@example.com']);

        $response = $this->postJson('/api/v1/users', [
            'name' => 'John Doe',
            'email' => 'john@example.com',
            'password' => 'password123',
        ]);

        $response->assertStatus(409);
    }
}

Use RefreshDatabase or DatabaseTransactions trait for isolation. Use Http facade fake for external API calls. Use Queue::fake() to test job dispatching. Use Bus::fake() to test command dispatching.

Rules

  • Controllers are thin — validation in Form Requests, business logic in Services.
  • Eloquent models have $fillable, $casts, type-hinted relations, and query scopes.
  • Form Requests contain validation rules and authorization logic.
  • Service classes are constructor-injected into controllers.
  • Queue jobs use typed constructor properties and $tries/$backoff for retry config.
  • API routes return JSON responses with Resource classes for DTO transformation.
  • Exception handling via Handler::render() for consistent error responses.
  • Caching with Cache::tags() for invalidatable cache groups.
  • All DB queries use eager loading (with()) to prevent N+1.
  • Migrations are always backward-compatible — never drop columns without deprecation.

References

  • references/artisan-commands.md — Artisan Commands
  • references/eloquent-orm.md — Eloquent ORM Patterns
  • references/laravel-middleware-validation.md — Middleware and Validation
  • references/laravel-queues.md — Queue Configuration
  • references/laravel-service-layer.md — Service Layer Pattern
  • references/laravel-testing.md — Testing Laravel

Handoff

Hand off to backend/php/pure/SKILL.md for non-Laravel PHP patterns or backend/universal/api-response/SKILL.md for API response formatting.

附带文件

技能加载后,模型会按需读取这些文件。它们仅作为可读文件提供,绝不会被执行。

常见问题

Php Laravel AI 技能有什么作用?

Use this skill when building Laravel applications — MVC structure, Eloquent ORM, service layer, validation, queues, and testing. This skill enforces: thin controllers, service layer for business logic, Eloquent best practices with eager loading, form request validation, and queue job structure. Requires Laravel 10+ or 11+. Do NOT use for: Symfony, WordPress, non-Laravel PHP frameworks.

为什么在 TypingMind 中使用 Php Laravel?

因为您只需安装一次,就能搭配任何模型使用。Php Laravel 采用纯 Markdown 格式,而非特定提供商专用的代码,因此同一技能可用于 GPT-5、Claude、Gemini、Grok 或本地模型。您甚至可以在聊天中途切换模型,而不会影响技能的正常使用。TypingMind 使用您自己的 API 密钥,因此您直接向提供商付费,而不是按席位订阅;您的技能和聊天记录也都保留在您自己的存储空间中。

如何在 TypingMind 中安装 Php Laravel?

在 TypingMind 中打开“插件 → 技能 → 从 GitHub 安装”,然后粘贴 https://github.com/j4flmao/agent-skills/tree/main/skills/backend/php/laravel。TypingMind 会读取其中的 SKILL.md,打包相关文件,并将其安装为技能,供您在各个聊天中按需启用。

哪些 AI 模型可以使用 Php Laravel?

您在 TypingMind 中连接的任何模型都可以。AI 技能采用纯 Markdown 指令,而非特定提供商专用的代码,因此 GPT、Claude、Gemini、Grok 和本地模型都能在请求匹配时加载此技能。

Php Laravel 可以搭配多少个 AI 模型使用?

数量不限。只要模型支持技能,您就可以将它与 Php Laravel 搭配使用。GPT、Claude、Gemini、Grok、DeepSeek、Mistral、Llama 等模型都可以通过您自己的 API 密钥接入 TypingMind。

Php Laravel AI 技能免费吗?

是的。j4flmao 已在 GitHub 上根据 MIT 许可证发布了该技能。您只需向自己的 AI 提供商支付所用 Token 的费用。

什么是 AI 技能?

AI 技能是一组可复用的指令,用于教会 AI 模型完成某项特定任务。它遵循开放的 Agent Skills 格式:包含名称和描述的 SKILL.md 文件,以及模型可能需要的脚本、模板或参考文件。模型仅在您的请求与技能匹配时才会读取这些指令,因此已安装的技能在使用前不会产生任何费用。

AI 技能与插件或 MCP 服务器有何不同?

插件或 MCP 服务器为模型提供可调用的新工具,也就是在某处运行并返回结果的代码。AI 技能则为模型提供知识和流程:如何处理任务、遵循哪些步骤,以及怎样的输出才算优质。技能采用纯 Markdown 格式,因此不需要服务器、API 密钥或运行时环境,并且适用于任何模型。

查看全部

立即创建您自己的 AI 工作区

订阅我们的电子简报,获取新功能和后续赠奖活动的通知 👇