eloquent-best-practices by iserter/laravel-claude-agents
npx skills add https://github.com/iserter/laravel-claude-agents --skill eloquent-best-practices// ❌ N+1 查询问题
$posts = Post::all();
foreach ($posts as $post) {
echo $post->user->name; // N 次额外查询
}
// ✅ 预加载
$posts = Post::with('user')->get();
foreach ($posts as $post) {
echo $post->user->name; // 无额外查询
}
// ❌ 获取所有列
$users = User::all();
// ✅ 仅需列
$users = User::select(['id', 'name', 'email'])->get();
// ✅ 包含关联关系
$posts = Post::with(['user:id,name'])->select(['id', 'title', 'user_id'])->get();
// ✅ 定义可复用的查询逻辑
class 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);
}
}
// 使用
$posts = Post::published()->popular()->get();
广告位招租
在这里展示您的产品或服务
触达数万 AI 开发者,精准高效
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);
}
}
// ❌ 触发额外查询
foreach ($posts as $post) {
echo $post->comments()->count();
}
// ✅ 高效加载计数
$posts = Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
class Post extends Model
{
// ✅ 白名单可填充属性
protected $fillable = ['title', 'content', 'status'];
// 或黑名单受保护属性
protected $guarded = ['id', 'user_id'];
// ❌ 切勿这样做
// protected $guarded = [];
}
class Post extends Model
{
protected $casts = [
'published_at' => 'datetime',
'metadata' => 'array',
'is_featured' => 'boolean',
'views' => 'integer',
];
}
// ✅ 分块处理以节省内存
Post::chunk(200, function ($posts) {
foreach ($posts as $post) {
// 处理每篇文章
}
});
// ✅ 或使用惰性集合
Post::lazy()->each(function ($post) {
// 每次处理一个
});
// ❌ 慢 - 先加载到内存
$posts = Post::where('status', 'draft')->get();
foreach ($posts as $post) {
$post->update(['status' => 'archived']);
}
// ✅ 快 - 单次查询
Post::where('status', 'draft')->update(['status' => 'archived']);
// ✅ 递增/递减
Post::where('id', $id)->increment('views');
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();
});
}
}
// ❌ 错误做法
foreach ($userIds as $id) {
$user = User::find($id);
}
// ✅ 正确做法
$users = User::whereIn('id', $userIds)->get();
// 迁移
Schema::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();
// 常用查询的复合索引
$table->index(['status', 'published_at']);
});
// 在 AppServiceProvider 的 boot 方法中
Model::preventLazyLoading(!app()->isProduction());
每周安装量
752
代码仓库
GitHub 星标数
29
首次出现
2026年1月22日
安全审计
安装于
opencode618
codex590
gemini-cli589
github-copilot562
kimi-cli479
cursor477
// ❌ 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
}
// ❌ 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();
// ✅ Define reusable query logic
class 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();
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);
}
}
// ❌ Triggers additional queries
foreach ($posts as $post) {
echo $post->comments()->count();
}
// ✅ Load counts efficiently
$posts = Post::withCount('comments')->get();
foreach ($posts as $post) {
echo $post->comments_count;
}
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 = [];
}
class Post extends Model
{
protected $casts = [
'published_at' => 'datetime',
'metadata' => 'array',
'is_featured' => 'boolean',
'views' => 'integer',
];
}
// ✅ Process in chunks to save memory
Post::chunk(200, function ($posts) {
foreach ($posts as $post) {
// Process each post
}
});
// ✅ Or use lazy collections
Post::lazy()->each(function ($post) {
// Process one at a time
});
// ❌ Slow - loads into memory first
$posts = Post::where('status', 'draft')->get();
foreach ($posts as $post) {
$post->update(['status' => 'archived']);
}
// ✅ Fast - single query
Post::where('status', 'draft')->update(['status' => 'archived']);
// ✅ Increment/decrement
Post::where('id', $id)->increment('views');
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();
});
}
}
// ❌ Bad
foreach ($userIds as $id) {
$user = User::find($id);
}
// ✅ Good
$users = User::whereIn('id', $userIds)->get();
// Migration
Schema::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']);
});
// In AppServiceProvider boot method
Model::preventLazyLoading(!app()->isProduction());
Weekly Installs
752
Repository
GitHub Stars
29
First Seen
Jan 22, 2026
Security Audits
Gen Agent Trust HubPassSocketPassSnykPass
Installed on
opencode618
codex590
gemini-cli589
github-copilot562
kimi-cli479
cursor477
ESLint迁移到Oxlint完整指南:JavaScript/TypeScript项目性能优化工具
1,000 周安装