Token导航 LogoToken导航TokenDH.com
开发规范需要联网github未标认证来源可访问clear审计通过

laravel-best-practicesLaravel 最佳实践

Agent Skill

laravel-best-practices 用于记录任务执行中的错误、用户纠正、经验和能力缺口,适合在 Codex、Claude、Cursor、Gemini CLI 中希望让 Agent 持续沉淀问题、修正和最佳实践时使用。可结合来源仓库、安装命令和原始 README 继续核验具体用法。安装前建议确认权限范围、维护状态,以及是否会触发联网、命令执行或文件读写。

总安装

19,341

周安装

814

GitHub Stars

33

下载量

6,772
CodexClaudeCursorGemini CLI

安装说明

本站只整理中文说明和来源信息,不托管安装包,也不代用户安装。

GitHub

来源数

3

许可证

MIT

最后核验

2026-05-01

来源状态

来源可访问

安装方式

通过对话安装

复制提示词发给支持本地命令或 Skills 的 AI 助手,先确认命令和权限,再让它执行。

请帮我安装这个 Agent Skill:laravel-best-practices(Laravel 最佳实践)
来源仓库:https://github.com/asyrafhussin/agent-skills
仓库路径:skills/laravel-best-practices
安装命令:
npx skills add https://github.com/asyrafhussin/agent-skills --skill laravel-best-practices
安装前请先检查当前环境是否支持对应 CLI,并向我确认将要执行的命令、安装目录、联网范围和文件读写权限;确认后再执行。

命令行安装

复制命令到本机终端执行。不同来源提供的安装方式可能略有差异;本站展示可直接复制的安装命令,安装前请核对来源页面。

skills.shnpx skills
npx skills add https://github.com/asyrafhussin/agent-skills --skill laravel-best-practices

简介

31 Laravel 13 跨架构、Eloquent、控制器、验证、安全性和 API 设计的约定和最佳实践。

  • 按优先级分为 7 个规则类别,从关键架构和数据库模式到中等影响的性能和 API 设计指南
  • 涵盖基本模式,包括服务类、表单请求、Eloquent 模型、迁移、急切加载和事件驱动架构
  • 包括 31 个带前缀的特定规则(例如 arch-service-classes, 雄辩的热切加载, 验证表单请求) 以便于参考和代理触发
  • 具有控制器、模型、迁移和常见模式(如 N+1 查询预防和事务处理)的完整代码示例
  • 以 PHP 8.3+ 为目标的 Laravel 13.x,包括 Laravel 13 特定的功能,如队列路由和 pgvector 语义搜索

SKILL.md

Laravel 13 Best Practices

Comprehensive best practices guide for Laravel 13 applications. Contains 31 rules across 7 categories for building scalable, maintainable Laravel applications.

When to Apply

Reference these guidelines when:

  • Creating controllers, models, and services
  • Writing migrations and database queries
  • Implementing validation and form requests
  • Building APIs with Laravel
  • Structuring Laravel applications

Rule Categories by Priority

PriorityCategoryImpactPrefix
1Architecture & StructureCRITICALarch-
2Eloquent & DatabaseCRITICALeloquent-
3Controllers & RoutingHIGHcontroller-, ctrl-
4Validation & RequestsHIGHvalidation-, valid-
5SecurityHIGHsec-
6PerformanceMEDIUMperf-
7API DesignMEDIUMapi-

Quick Reference

1. Architecture & Structure (CRITICAL)

  • arch-service-classes - Extract business logic to services
  • arch-action-classes - Single-purpose action classes
  • arch-repository-pattern - When to use repositories
  • arch-dto-pattern - Data transfer objects
  • arch-value-objects - Encapsulate domain concepts
  • arch-event-driven - Decouple with events and listeners
  • arch-feature-folders - Organize by domain/feature
  • arch-queue-routing - Centralized job queue routing (Laravel 13+)

2. Eloquent & Database (CRITICAL)

  • eloquent-eager-loading - Prevent N+1 queries
  • eloquent-chunking - Process large datasets
  • eloquent-query-scopes - Reusable query logic
  • eloquent-model-events - Use observers for side effects
  • eloquent-relationships - Define relationships properly
  • eloquent-casts - Automatic attribute casting
  • eloquent-accessors-mutators - Transform attributes
  • eloquent-soft-deletes - Safe deletion with recovery
  • eloquent-pruning - Automatic cleanup of old records
  • eloquent-vector-search - Semantic search with pgvector (Laravel 13+)

3. Controllers & Routing (HIGH)

  • controller-resource-controllers - Use resource controllers
  • controller-single-action - Single action invokable controllers
  • controller-resource-methods - RESTful resource methods
  • controller-form-requests - Use form requests
  • controller-api-resources - Transform API responses
  • controller-middleware - Apply middleware properly
  • controller-dependency-injection - Inject dependencies

4. Validation & Requests (HIGH)

  • validation-form-requests - Use form request classes
  • validation-custom-rules - Create custom rules
  • validation-conditional-rules - Conditional validation
  • validation-array-validation - Validate nested arrays
  • validation-after-hooks - Complex validation logic

5. Security (HIGH)

  • sec-mass-assignment - Protect against mass assignment

6. Performance (MEDIUM)

No rule files exist yet for this category.

7. API Design (MEDIUM)

No rule files exist yet for this category.

Essential Patterns

Controller with Form Request

<?php

namespace App\Http\Controllers;

use App\Http\Requests\StorePostRequest;
use App\Http\Requests\UpdatePostRequest;
use App\Models\Post;
use Illuminate\Http\RedirectResponse;

class PostController extends Controller
{
    public function store(StorePostRequest $request): RedirectResponse
    {
        // Validation happens automatically
        $validated = $request->validated();

        $post = Post::create($validated);

        return redirect()
            ->route('posts.show', $post)
            ->with('success', 'Post created successfully.');
    }

    public function update(UpdatePostRequest $request, Post $post): RedirectResponse
    {
        $post->update($request->validated());

        return redirect()
            ->route('posts.show', $post)
            ->with('success', 'Post updated successfully.');
    }
}

Form Request Class

<?php

namespace App\Http\Requests;

use Illuminate\Foundation\Http\FormRequest;

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

    public function rules(): array
    {
        return [
            'title' => ['required', 'string', 'max:255'],
            'body' => ['required', 'string', 'min:100'],
            'category_id' => ['required', 'exists:categories,id'],
            'tags' => ['nullable', 'array'],
            'tags.*' => ['exists:tags,id'],
            'published_at' => ['nullable', 'date', 'after:now'],
        ];
    }

    public function messages(): array
    {
        return [
            'body.min' => 'The post body must be at least 100 characters.',
        ];
    }
}

Service Class Pattern

<?php

namespace App\Services;

use App\Models\User;
use App\Models\Post;
use App\Events\PostPublished;
use Illuminate\Support\Facades\DB;

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

    public function publish(Post $post): Post
    {
        return DB::transaction(function () use ($post) {
            $post->update([
                'published_at' => now(),
                'status' => 'published',
            ]);

            event(new PostPublished($post));

            $this->notifications->notifyFollowers($post->author, $post);

            return $post->fresh();
        });
    }
}

Eloquent Model

<?php

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\BelongsToMany;
use Illuminate\Database\Eloquent\Builder;

class Post extends Model
{
    use HasFactory;

    protected $fillable = [
        'title',
        'slug',
        'body',
        'category_id',
        'published_at',
    ];

    protected $casts = [
        'published_at' => 'datetime',
    ];

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

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    public function tags(): BelongsToMany
    {
        return $this->belongsToMany(Tag::class)->withTimestamps();
    }

    // Scopes
    public function scopePublished(Builder $query): Builder
    {
        return $query->whereNotNull('published_at')
            ->where('published_at', '<=', now());
    }

    public function scopeByCategory(Builder $query, int $categoryId): Builder
    {
        return $query->where('category_id', $categoryId);
    }

    // Accessors & Mutators
    protected function title(): Attribute
    {
        return Attribute::make(
            set: fn (string $value) => ucfirst($value),
        );
    }
}

Migration Best Practices

<?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) {
            $table->id();
            $table->foreignId('user_id')->constrained()->cascadeOnDelete();
            $table->foreignId('category_id')->constrained()->cascadeOnDelete();
            $table->string('title');
            $table->string('slug')->unique();
            $table->text('body');
            $table->timestamp('published_at')->nullable();
            $table->timestamps();

            // Indexes for common queries
            $table->index(['user_id', 'published_at']);
            $table->index('category_id');
        });
    }

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

Eager Loading

// N+1 Problem
$posts = Post::all();
foreach ($posts as $post) {
    echo $post->author->name;  // Query per post
}

// Eager loading — only 3 queries total
$posts = Post::with(['author', 'category', 'tags'])->get();
foreach ($posts as $post) {
    echo $post->author->name;  // No additional queries
}

// Nested eager loading
$posts = Post::with([
    'author.profile',
    'comments.user',
    'tags',
])->get();

// Constrained eager loading
$posts = Post::with([
    'comments' => fn ($query) => $query->latest()->limit(5),
])->get();

How to Use

Read individual rule files for detailed explanations and code examples:

rules/arch-service-classes.md
rules/eloquent-eager-loading.md
rules/validation-form-requests.md
rules/_sections.md

Each rule file contains:

  • YAML frontmatter with metadata (title, impact, tags)
  • Brief explanation of why it matters
  • Bad Example with explanation
  • Good Example with explanation
  • Laravel 13 and PHP 8.3 specific context and references

Full Compiled Document

For the complete guide with all rules expanded: AGENTS.md

适合场景

01

用户想查找某类 Agent Skill 时

02

需要根据任务场景推荐可安装能力包时

03

需要对比不同来源的安装命令和来源信息时

04

需要参考平台分布和安装热度时

能力概览

能力 1

按任务关键词查找相关 Skills

能力 2

展示可复制的安装命令

能力 3

保留来源站点、仓库和原始说明,方便继续核验

能力 4

补充不同宿主或平台的使用分布数据

能力 5

展示第三方安全扫描或审计结果

安装后应在对应宿主中按原始 README 的触发条件使用;具体调用方式请以来源页面和 README 为准。

平台分布

Claude Code

27.4%
按下载量换算1,856

Antigravity

21.83%
按下载量换算1,478

OpenCode

18.63%
按下载量换算1,262

Codex

11.38%
按下载量换算771

Cursor

7.89%
按下载量换算534

windsurf

3.09%
按下载量换算209

安全审计

Gen Agent Trust Hub

通过

Socket

通过

Snyk

通过

权限和风险

需要联网

该 Skill 可能需要联网访问来源站点、仓库或外部 API;具体网络访问范围需要结合源码和 README 复核。

安装前确认

本站仅展示第三方公开信息,不托管安装包,不提供自动安装或运行环境。安装前应自行审查源码、依赖和命令行为。

来源信息

继续浏览同类 Skills