Eloquent Best Practices

iSerter/laravel-claude-agents/skills/eloquent-best-practices

作者 iSerter8868214ee3fe0eee4e865dd07dbb9832a05b6ddc无许可证收录于 2026年10月9日更新于 2026年10月9日

Best practices for Laravel Eloquent ORM including query optimization, relationship management, and avoiding common pitfalls like N+1 queries.

AI 生成的概览

关于 Laravel Eloquent ORM 最佳实践的指导,涵盖查询优化、关系管理和避免 N+1 查询。

功能
该技能提供编写高效 Laravel Eloquent ORM 代码的参考指导和代码示例。内容涵盖预加载、列选择、查询作用域、关系返回类型、withCount、批量赋值保护、类型转换、分块处理、数据库级操作、模型事件、索引以及防止延迟加载。它产出说明性代码片段和检查清单,而不是可执行脚本。
适用场景
适用于处理 Laravel Eloquent 模型和查询时,尤其是优化性能、修复 N+1 查询问题,或审查关系与批量赋值模式。也适合在审查基于 Eloquent 的代码时作为检查清单使用。
运行要求
不需要脚本或特殊工具,仅为说明和代码示例。假定使用带有 Eloquent 的 Laravel 项目。

Eloquent Best Practices

Query Optimization

Always Eager Load Relationships

php
// ❌ N+1 Query Problem$posts = Post::all();foreach ($posts as $post) {    echo $post->user->name; // N additional queries}
// ✅ Eager Loading$posts = Post::with('user')->get();foreach ($posts as $post) {    echo $post->user->name; // No additional queries}

Select Only Needed Columns

php
// ❌ Fetches all columns$users = User::all();
// ✅ Only needed columns$users = User::select(['id', 'name', 'email'])->get();
// ✅ With relationships$posts = Post::with(['user:id,name'])->select(['id', 'title', 'user_id'])->get();

Use Query Scopes

php
// ✅ Define reusable query logicclass Post extends Model{    public function scopePublished($query)    {        return $query->where('status', 'published')                    ->whereNotNull('published_at');    }        public function scopePopular($query, $threshold = 100)    {        return $query->where('views', '>', $threshold);    }}
// Usage$posts = Post::published()->popular()->get();

Relationship Best Practices

Define Return Types

php
use Illuminate\Database\Eloquent\Relations\BelongsTo;use Illuminate\Database\Eloquent\Relations\HasMany;
class Post extends Model{    public function user(): BelongsTo    {        return $this->belongsTo(User::class);    }        public function comments(): HasMany    {        return $this->hasMany(Comment::class);    }}

Use withCount for Counts

php
// ❌ Triggers additional queriesforeach ($posts as $post) {    echo $post->comments()->count();}
// ✅ Load counts efficiently$posts = Post::withCount('comments')->get();foreach ($posts as $post) {    echo $post->comments_count;}

Mass Assignment Protection

php
class Post extends Model{    // ✅ Whitelist fillable attributes    protected $fillable = ['title', 'content', 'status'];        // Or blacklist guarded attributes    protected $guarded = ['id', 'user_id'];        // ❌ Never do this    // protected $guarded = [];}

Use Casts for Type Safety

php
class Post extends Model{    protected $casts = [        'published_at' => 'datetime',        'metadata' => 'array',        'is_featured' => 'boolean',        'views' => 'integer',    ];}

Chunking for Large Datasets

php
// ✅ Process in chunks to save memoryPost::chunk(200, function ($posts) {    foreach ($posts as $post) {        // Process each post    }});
// ✅ Or use lazy collectionsPost::lazy()->each(function ($post) {    // Process one at a time});

Database-Level Operations

php
// ❌ Slow - loads into memory first$posts = Post::where('status', 'draft')->get();foreach ($posts as $post) {    $post->update(['status' => 'archived']);}
// ✅ Fast - single queryPost::where('status', 'draft')->update(['status' => 'archived']);
// ✅ Increment/decrementPost::where('id', $id)->increment('views');

Use Model Events Wisely

php
class Post extends Model{    protected static function booted()    {        static::creating(function ($post) {            $post->slug = Str::slug($post->title);        });                static::deleting(function ($post) {            $post->comments()->delete();        });    }}

Common Pitfalls to Avoid

Don't Query in Loops

php
// ❌ Badforeach ($userIds as $id) {    $user = User::find($id);}
// ✅ Good$users = User::whereIn('id', $userIds)->get();

Don't Forget Indexes

php
// MigrationSchema::create('posts', function (Blueprint $table) {    $table->id();    $table->foreignId('user_id')->constrained()->index();    $table->string('slug')->unique();    $table->string('status')->index();    $table->timestamp('published_at')->nullable()->index();        // Composite index for common queries    $table->index(['status', 'published_at']);});

Prevent Lazy Loading in Development

php
// In AppServiceProvider boot methodModel::preventLazyLoading(!app()->isProduction());

Checklist

  • Relationships eagerly loaded where needed
  • Only selecting required columns
  • Using query scopes for reusability
  • Mass assignment protection configured
  • Appropriate casts defined
  • Indexes on foreign keys and query columns
  • Using database-level operations when possible
  • Chunking for large datasets
  • Model events used appropriately
  • Lazy loading prevented in development

来源与署名

来源:iSerter/laravel-claude-agents位于skills/eloquent-best-practices提交8868214

许可证: 无许可证

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

举报或申请下架