Laravel Specialist

作者 jeffallan1be15d8064f8MIT11K 个星标收录于 2026年10月8日更新于 2026年10月8日仓库5天前更新

Build and configure Laravel 10+ applications, including creating Eloquent models and relationships, implementing Sanctum authentication, configuring Horizon queues, designing RESTful APIs with API resources, and building reactive interfaces with Livewire. Use when creating Laravel models, setting up queue workers, implementing Sanctum auth flows, building Livewire components, optimising Eloquent queries, or writing Pest/PHPUnit tests for Laravel features.

AI 生成的概览

指导 Laravel 10+ 后端开发:Eloquent 模型、API、队列、Livewire 与测试。

功能
提供构建 Laravel 10+ 应用的结构化工作流与代码模板,面向 PHP 8.2+。内容涵盖 Eloquent 模型与关联、迁移、API 资源、Sanctum 认证、Horizon 队列、Livewire 组件以及 Pest/PHPUnit 测试,并为每个主题提供参考文件。还列出编码约束、验证检查点以及用于确认迁移、路由、任务和测试覆盖率的 Artisan 命令。
适用场景
适用于创建或扩展 Laravel 应用的场景,例如定义 Eloquent 模型与关联、构建 RESTful API、配置队列工作进程、实现认证流程,或编写 Laravel 功能测试与单元测试。
运行要求
需要 Laravel 10+ 项目、PHP 8.2+、Composer 依赖、Artisan 命令行,以及 Pest 或 PHPUnit 等测试运行器;队列相关工作还涉及 Redis 与 Horizon。该技能不包含脚本,仅提供参考文档。

Laravel Specialist

Senior Laravel specialist with deep expertise in Laravel 10+, Eloquent ORM, and modern PHP 8.2+ development.

Core Workflow

  1. Analyse requirements — Identify models, relationships, APIs, and queue needs
  2. Design architecture — Plan database schema, service layers, and job queues
  3. Implement models — Create Eloquent models with relationships, scopes, and casts; run php artisan make:model and verify with php artisan migrate:status
  4. Build features — Develop controllers, services, API resources, and jobs; run php artisan route:list to verify routing
  5. Test thoroughly — Write feature and unit tests; run php artisan test before considering any step complete (target >85% coverage)

Reference Guide

Load detailed guidance based on context:

TopicReferenceLoad When
Eloquent ORMreferences/eloquent.mdModels, relationships, scopes, query optimization
Routing & APIsreferences/routing.mdRoutes, controllers, middleware, API resources
Queue Systemreferences/queues.mdJobs, workers, Horizon, failed jobs, batching
Livewirereferences/livewire.mdComponents, wire:model, actions, real-time
Testingreferences/testing.mdFeature tests, factories, mocking, Pest PHP

Constraints

MUST DO

  • Use PHP 8.2+ features (readonly, enums, typed properties)
  • Type hint all method parameters and return types
  • Use Eloquent relationships properly (avoid N+1 with eager loading)
  • Implement API resources for transforming data
  • Queue long-running tasks
  • Write comprehensive tests (>85% coverage)
  • Use service containers and dependency injection
  • Follow PSR-12 coding standards

MUST NOT DO

  • Use raw queries without protection (SQL injection)
  • Skip eager loading (causes N+1 problems)
  • Store sensitive data unencrypted
  • Mix business logic in controllers
  • Hardcode configuration values
  • Skip validation on user input
  • Use deprecated Laravel features
  • Ignore queue failures

Code Templates

Use these as starting points for every implementation.

Eloquent Model

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;use Illuminate\Database\Eloquent\SoftDeletes;
final class Post extends Model{    use HasFactory, SoftDeletes;
    protected $fillable = ['title', 'body', 'status', 'user_id'];
    protected $casts = [        'status' => PostStatus::class, // backed enum        'published_at' => 'immutable_datetime',    ];
    // Relationships — always eager-load via ::with() at call site    public function author(): BelongsTo    {        return $this->belongsTo(User::class, 'user_id');    }
    public function comments(): HasMany    {        return $this->hasMany(Comment::class);    }
    // Local scope    public function scopePublished(Builder $query): Builder    {        return $query->where('status', PostStatus::Published);    }}

Migration

php
<?php
use Illuminate\Database\Migrations\Migration;use Illuminate\Database\Schema\Blueprint;use Illuminate\Support\Facades\Schema;
return new class extends Migration{    public function up(): void    {        Schema::create('posts', function (Blueprint $table): void {            $table->id();            $table->foreignId('user_id')->constrained()->cascadeOnDelete();            $table->string('title');            $table->text('body');            $table->string('status')->default('draft');            $table->timestamp('published_at')->nullable();            $table->softDeletes();            $table->timestamps();        });    }
    public function down(): void    {        Schema::dropIfExists('posts');    }};

API Resource

php
<?php
declare(strict_types=1);
namespace App\Http\Resources;
use Illuminate\Http\Request;use Illuminate\Http\Resources\Json\JsonResource;
final class PostResource extends JsonResource{    public function toArray(Request $request): array    {        return [            'id'           => $this->id,            'title'        => $this->title,            'body'         => $this->body,            'status'       => $this->status->value,            'published_at' => $this->published_at?->toIso8601String(),            'author'       => new UserResource($this->whenLoaded('author')),            'comments'     => CommentResource::collection($this->whenLoaded('comments')),        ];    }}

Queued Job

php
<?php
declare(strict_types=1);
namespace App\Jobs;
use App\Models\Post;use Illuminate\Bus\Queueable;use Illuminate\Contracts\Queue\ShouldQueue;use Illuminate\Foundation\Bus\Dispatchable;use Illuminate\Queue\InteractsWithQueue;use Illuminate\Queue\SerializesModels;
final class PublishPost implements ShouldQueue{    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
    public int $tries = 3;    public int $backoff = 60;
    public function __construct(        private readonly Post $post,    ) {}
    public function handle(): void    {        $this->post->update([            'status'       => PostStatus::Published,            'published_at' => now(),        ]);    }
    public function failed(\Throwable $e): void    {        // Log or notify — never silently swallow failures        logger()->error('PublishPost failed', ['post' => $this->post->id, 'error' => $e->getMessage()]);    }}

Feature Test (Pest)

php
<?php
use App\Models\Post;use App\Models\User;
it('returns a published post for authenticated users', function (): void {    $user = User::factory()->create();    $post = Post::factory()->published()->for($user, 'author')->create();
    $response = $this->actingAs($user)        ->getJson("/api/posts/{$post->id}");
    $response->assertOk()        ->assertJsonPath('data.status', 'published')        ->assertJsonPath('data.author.id', $user->id);});
it('queues a publish job when a draft is submitted', function (): void {    Queue::fake();    $user = User::factory()->create();    $post = Post::factory()->draft()->for($user, 'author')->create();
    $this->actingAs($user)        ->postJson("/api/posts/{$post->id}/publish")        ->assertAccepted();
    Queue::assertPushed(PublishPost::class, fn ($job) => $job->post->is($post));});

Validation Checkpoints

Run these at each workflow stage to confirm correctness before proceeding:

StageCommandExpected Result
After migrationphp artisan migrate:statusAll migrations show Ran
After routingphp artisan route:list --path=apiNew routes appear with correct verbs
After job dispatchphp artisan queue:work --onceJob processes without exception
After implementationphp artisan test --coverage>85% coverage, 0 failures
Before PR./vendor/bin/pint --testPSR-12 linting passes

Knowledge Reference

Laravel 10+, Eloquent ORM, PHP 8.2+, API resources, Sanctum/Passport, queues, Horizon, Livewire, Inertia, Octane, Pest/PHPUnit, Redis, broadcasting, events/listeners, notifications, task scheduling

Maintained by @jeffallan, Principal Consultant at Synergetic Solutions

Documentation

来源与署名

来源:jeffallan/claude-skills位于skills/laravel-specialist提交1be15d8

许可证: MIT

内容归原作者所有。SourceWeft 从公开仓库中收录这些内容。

举报或申请下架