Laravel 标志

Laravel

社区
Omar-Obando
laravel

Laravel PHP framework development patterns — Eloquent ORM with factories and relationships, Form Requests for validation, Service Container and dependency injection, API resources for JSON APIs, Blade templating, queue jobs with ShouldQueue, middleware layers, policy-based authorization, migrations, and artisan commands.

Add to TypingMind

概览

发布者Omar-Obando
代码仓库qwen-orchestrator
技能名称laravel
星标数
53
复刻数
13
附带文件
仅含指令
许可协议MIT
链接
  • Markdown 格式的指令

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

  • 兼容任何大语言模型

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

  • 指令自成一体

    模型所需的一切都包含在指令中,无需同步额外文件。

  • 开源

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

安装

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

1

安装到 TypingMind

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

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

安装到其他智能体

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

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

在 TypingMind 中使用此技能

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

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

兼容任何 AI 模型

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

  • 仅在需要时加载

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

  • 在聊天中切换模型

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

技能指令

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

Laravel Development Skill — PHP Framework Mastery

This skill provides comprehensive Laravel development patterns following convention-over-configuration principles, Eloquent-first data access, and enterprise-grade architecture.

Key Principles

  • Convention over Configuration: Follow Laravel naming conventions for zero-config discovery
  • Eloquent-First: Use ORM for all data access; raw SQL only for complex queries
  • Validation at the Edge: Form Requests validate before reaching controllers
  • Thin Controllers, Fat Models: Business logic in models and services, not controllers

Project Scaffolding

Model Creation (All-in-One)

bash
php artisan make:model Product -crR
# Creates: Model + Controller (resource) + Form Requests + API Resource
FlagCreates
-cController
-rResource controller (CRUD methods)
-RForm Requests (StoreRequest, UpdateRequest)
-mMigration
-fFactory
-sSeeder

Eloquent ORM

Relationships

php
class User extends Model
{
    // One-to-One
    public function profile(): HasOne
    {
        return $this->hasOne(Profile::class);
    }

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

    // Inverse: belongsTo (on the child model)
    public function author(): BelongsTo
    {
        return $this->belongsTo(User::class, 'author_id');
    }

    // Many-to-Many (pivot table)
    public function roles(): BelongsToMany
    {
        return $this->belongsToMany(Role::class)
            ->withPivot('assigned_at')
            ->withTimestamps();
    }

    // Polymorphic
    public function comments(): MorphMany
    {
        return $this->morphMany(Comment::class, 'commentable');
    }

    // Has-One-Through
    public function license(): HasOneThrough
    {
        return $this->hasOneThrough(License::class, Subscription::class);
    }
}

Eager Loading (Prevent N+1)

php
// BAD: N+1 query — one query per post to get author
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->author->name; // N queries
}

// GOOD: Eager load with 2 queries total
$posts = Post::with('author', 'comments.user')->get();
foreach ($posts as $post) {
    echo $post->author->name; // No additional queries
}

// Conditional eager loading
$posts = Post::with(['comments' => function ($query) {
    $query->where('is_approved', true)->latest();
}])->get();

// Lazy eager loading (load only when needed)
$posts = Post::all();
if ($needComments) {
    $posts->load('comments');
}

Factories and Seeders

php
// database/factories/ProductFactory.php
class ProductFactory extends Factory
{
    public function definition(): array
    {
        return [
            'name' => fake()->words(3, true),
            'sku' => fake()->unique()->ean8(),
            'price' => fake()->randomFloat(2, 5, 500),
            'description' => fake()->paragraphs(3, true),
            'is_active' => true,
            'category_id' => Category::factory(),
        ];
    }

    public function inactive(): static
    {
        return $this->state(fn (array $attributes) => [
            'is_active' => false,
        ]);
    }
}

// database/seeders/DatabaseSeeder.php
class DatabaseSeeder extends Seeder
{
    public function run(): void
    {
        Category::factory(10)->create();
        Product::factory(100)
            ->has(Review::factory()->count(3))
            ->create();
    }
}

Scopes, Accessors, and Mutators

php
class Product extends Model
{
    // Query Scope
    public function scopeActive(Builder $query): Builder
    {
        return $query->where('is_active', true);
    }

    public function scopeInStock(Builder $query): Builder
    {
        return $query->where('stock_count', '>', 0);
    }

    // Accessor (computed attribute)
    protected function formattedPrice(): Attribute
    {
        return Attribute::make(
            get: fn (mixed $value, array $attributes) =>
                '$' . number_format($attributes['price'], 2),
        );
    }

    // Mutator (transform on set)
    protected function name(): Attribute
    {
        return Attribute::make(
            get: fn (string $value) => ucfirst($value),
            set: fn (string $value) => strtolower(trim($value)),
        );
    }

    // Casts
    protected function casts(): array
    {
        return [
            'price' => 'decimal:2',
            'is_active' => 'boolean',
            'metadata' => 'array',
            'published_at' => 'datetime',
            'tags' => 'collection',
        ];
    }
}

Form Requests (Validation at the Edge)

php
// php artisan make:request StoreProductRequest
class StoreProductRequest extends FormRequest
{
    public function authorize(): bool
    {
        return $this->user()->can('create', Product::class);
    }

    public function rules(): array
    {
        return [
            'name' => ['required', 'string', 'max:255'],
            'sku' => ['required', 'string', 'unique:products,sku'],
            'price' => ['required', 'numeric', 'min:0', 'max:999999.99'],
            'description' => ['nullable', 'string', 'max:5000'],
            'category_id' => ['required', 'exists:categories,id'],
            'is_active' => ['boolean'],
            'tags' => ['array'],
            'tags.*' => ['string', 'max:50'],
        ];
    }

    public function messages(): array
    {
        return [
            'sku.unique' => 'This SKU is already in use.',
            'price.max' => 'Price cannot exceed 999,999.99.',
        ];
    }

    // Prepare data before validation
    protected function prepareForValidation(): void
    {
        $this->merge([
            'sku' => strtoupper(trim($this->sku)),
        ]);
    }
}

Service Container and Dependency Injection

Automatic Injection

php
class ProductController extends Controller
{
    // Automatic resolution via constructor
    public function __construct(
        private readonly ProductRepository $products,
    ) {}

    // Automatic resolution via method
    public function show(Product $product): ProductResource
    {
        return new ProductResource($product);
    }
}

Binding

php
// AppServiceProvider.php
public function register(): void
{
    // Interface → Implementation
    $this->app->bind(
        PaymentGatewayInterface::class,
        StripeGateway::class
    );

    // Singleton (shared instance)
    $this->app->singleton(
        CacheService::class,
        fn () => new CacheService(config('cache.ttl'))
    );

    // Scoped (one per request cycle)
    $this->app->scoped(TenantManager::class);

    // Factory binding (new instance each time)
    $this->app->bind(ReportGenerator::class, function ($app) {
        return new ReportGenerator(
            $app->make(DataSource::class),
            $app->make(Formatter::class),
        );
    });
}

API Development

API Resources

php
class ProductResource extends JsonResource
{
    public function toArray(Request $request): array
    {
        return [
            'id' => $this->id,
            'name' => $this->name,
            'sku' => $this->sku,
            'price' => [
                'amount' => (float) $this->price,
                'currency' => 'USD',
                'formatted' => $this->formatted_price,
            ],
            'category' => new CategoryResource($this->whenLoaded('category')),
            'reviews_count' => $this->whenCounted('reviews'),
            'tags' => $this->whenLoaded('tags'),
            'created_at' => $this->created_at->toISOString(),
            'links' => [
                'self' => route('api.products.show', $this->id),
            ],
        ];
    }
}

// Collection with metadata
class ProductCollection extends ResourceCollection
{
    public function toArray(Request $request): array
    {
        return [
            'data' => $this->collection,
            'meta' => [
                'total' => $this->total(),
                'count' => $this->count(),
                'per_page' => $this->perPage(),
                'current_page' => $this->currentPage(),
            ],
        ];
    }
}

API Routes

php
// routes/api.php
Route::middleware(['auth:sanctum', 'throttle:api'])->group(function () {
    Route::apiResource('products', ProductController::class);

    Route::get('products/search', [ProductController::class, 'search']);

    Route::prefix('admin')->middleware('role:admin')->group(function () {
        Route::apiResource('users', Admin\UserController::class);
    });
});

Queues and Jobs

Job Classes

php
class ProcessProductImport implements ShouldQueue
{
    use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;

    public int $tries = 3;
    public int $backoff = 30;
    public bool $deleteWhenMissingModels = true;

    public function __construct(
        public readonly string $filePath,
        public readonly int $userId,
    ) {}

    public function handle(
        ProductImportService $importService,
        NotificationService $notifications,
    ): void {
        $result = $importService->import($this->filePath);

        $notifications->notifyUser($this->userId, new ImportComplete($result));
    }

    public function failed(\Throwable $exception): void
    {
        Log::error('Product import failed', [
            'file' => $this->filePath,
            'error' => $exception->getMessage(),
        ]);
    }
}

// Dispatch
ProcessProductImport::dispatch($filePath, auth()->id())
    ->onQueue('imports')
    ->delay(now()->addMinutes(5));

// Job chains
Bus::chain([
    new ValidateImportFile($path),
    new ProcessProductImport($path),
    new CleanupImportFile($path),
])->catch(function (\Throwable $e) {
    Log::error('Import chain failed: ' . $e->getMessage());
})->dispatch();

Middleware

php
// Custom middleware
class EnsureTenantScope
{
    public function handle(Request $request, Closure $next): Response
    {
        if ($tenant = $request->route('tenant')) {
            app(TenantManager::class)->setCurrent($tenant);
        }

        return $next($request);
    }
}

// Registration in bootstrap/app.php or Kernel.php
->withMiddleware(function (Middleware $middleware) {
    $middleware->appendToGroup('api', [
        \App\Http\Middleware\EnsureJsonResponse::class,
    ]);

    $middleware->alias([
        'tenant' => \App\Http\Middleware\EnsureTenantScope::class,
        'role' => \App\Http\Middleware\EnsureRole::class,
    ]);
});

Policy-Based Authorization

php
// php artisan make:policy ProductPolicy --model=Product
class ProductPolicy
{
    public function viewAny(User $user): bool
    {
        return $user->can('products.view');
    }

    public function view(User $user, Product $product): bool
    {
        return $user->belongsToTenant($product->tenant);
    }

    public function create(User $user): bool
    {
        return $user->can('products.create');
    }

    public function update(User $user, Product $product): bool
    {
        return $user->can('products.update')
            && $user->belongsToTenant($product->tenant);
    }

    // Super-admin bypass
    public function before(User $user, string $ability): bool|null
    {
        return $user->isSuperAdmin() ? true : null;
    }
}

// Usage in controller
class ProductController extends Controller
{
    public function update(UpdateProductRequest $request, Product $product)
    {
        $this->authorize('update', $product);
        // ...
    }
}

// Usage in Blade
@can('update', $product)
    <a href="{{ route('products.edit', $product) }}">Edit</a>
@endcan

Migrations

php
// php artisan make:migration create_products_table
return new class extends Migration
{
    public function up(): void
    {
        Schema::create('products', function (Blueprint $table) {
            $table->id();
            $table->foreignId('tenant_id')->constrained()->cascadeOnDelete();
            $table->foreignId('category_id')->nullable()->constrained()->nullOnDelete();
            $table->string('name');
            $table->string('sku')->unique();
            $table->decimal('price', 10, 2)->default(0);
            $table->text('description')->nullable();
            $table->json('metadata')->nullable();
            $table->boolean('is_active')->default(true);
            $table->unsignedInteger('stock_count')->default(0);
            $table->timestamp('published_at')->nullable();
            $table->softDeletes();
            $table->timestamps();

            // Indexes for common queries
            $table->index(['tenant_id', 'is_active']);
            $table->index('published_at');
            $table->fullText(['name', 'description']);
        });
    }

    public function down(): void
    {
        Schema::dropIfExists('products');
    }
};

Testing

Feature Tests with Pest

php
test('can list active products', function () {
    Product::factory(3)->create(['is_active' => true]);
    Product::factory(2)->create(['is_active' => false]);

    $response = $this->getJson('/api/products');

    $response->assertOk()
        ->assertJsonCount(3, 'data')
        ->assertJsonStructure([
            'data' => [
                '*' => ['id', 'name', 'price', 'category'],
            ],
        ]);
});

test('cannot create product without authentication', function () {
    $this->postJson('/api/products', [
        'name' => 'Test Product',
    ])->assertUnauthorized();
});

test('product belongs to user tenant', function () {
    $user = User::factory()->create();
    $product = Product::factory()->create(['tenant_id' => $user->tenant_id]);

    $response = $this->actingAs($user)
        ->getJson("/api/products/{$product->id}");

    $response->assertOk();
});

HTTP Test Assertions

php
$response->assertStatus(200);
$response->assertJson(['status' => 'success']);
$response->assertJsonPath('data.name', 'Test Product');
$response->assertJsonCount(10, 'data');
$response->assertJsonStructure(['data' => ['id', 'name']]);
$response->assertJsonValidationErrors(['email']);
$response->assertCreated();
$response->assertNotFound();
$response->assertForbidden();

Anti-Patterns

Anti-PatternProblemFix
Fat controllersHard to test, mixed concernsExtract to services/actions
Queries in Blade templatesN+1, slow renderingEager load in controller
No eager loadingN+1 queriesUse ::with() or ::load()
Raw SQL without bindingsSQL injectionUse Eloquent or parameterized queries
Ignoring mass assignmentSecurity vulnerabilityUse $fillable or $guarded on all models
Validation in controllersRepeated, hard to testUse Form Request classes
Business logic in routesNo reusabilityMove to controller or service
Not using database transactionsData inconsistencyWrap related operations in DB::transaction
Returning models directly from APIExposes internal structureUse API Resources for transformation
Catching all exceptions silentlyHidden bugsLog and handle specifically

When NOT to Use

Do NOT use this skill when:

  • Writing application business logic (use domain-driven skill)
  • Designing database schemas (use database-design skill)
  • Writing API endpoint implementations (use api-design skill)
  • Reviewing code for quality issues (use code-review skill)
  • Performing security audits (use security-auditor skill)
  • Analyzing deployment configurations (use deployment skill)
  • Writing SQL queries (use sql-best-practices skill)
  • Designing multi-page website layouts (use design-system skill)

常见问题

Laravel AI 技能有什么作用?

Laravel PHP framework development patterns — Eloquent ORM with factories and relationships, Form Requests for validation, Service Container and dependency injection, API resources for JSON APIs, Blade templating, queue jobs with ShouldQueue, middleware layers, policy-based authorization, migrations, and artisan commands.

为什么在 TypingMind 中使用 Laravel?

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

如何在 TypingMind 中安装 Laravel?

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

哪些 AI 模型可以使用 Laravel?

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

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

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

Laravel AI 技能免费吗?

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

什么是 AI 技能?

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

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

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

查看全部

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

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