eloquent-expert
Advanced Eloquent ORM patterns including relationships, eager loading, factories, and query optimization.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
菜单
Advanced Eloquent ORM patterns including relationships, eager loading, factories, and query optimization.
用 Codex 或 Claude 帮你安装 复制这段 Prompt,粘贴到 Codex、Claude 或其他助手里,让它检查 Skill 页面并帮你完成安装。
基于 SOC 职业分类
PHP Artisan CLI patterns including make commands, flags, custom commands, and AI-friendly usage.
Laravel development best practices covering service providers, dependency injection, facades, and the Laravel Way.
Laravel Tinker best practices for debugging, testing ideas, and data exploration. When and how to use safely.
Laravel-native error handling patterns. Renderable exceptions, Livewire traits strategies, and user-facing notifications.
Integrate Anthropic Claude API with Laravel. HTTP client, message format, error handling. Use when calling Claude models from Laravel applications.
API security patterns for Laravel. Rate limiting, headers, CORS, Sanctum tokens, input validation. Use when building or securing API endpoints.
| name | eloquent-expert |
| description | Advanced Eloquent ORM patterns including relationships, eager loading, factories, and query optimization. |
public function posts(): HasMany
{
return $this->hasMany(Post::class);
}
public function author(): BelongsTo
{
return $this->belongsTo(User::class, 'user_id');
}
public function tags(): BelongsToMany
{
return $this->belongsToMany(Tag::class)->withTimestamps();
}
| Type | Model A | Model B | Use Case |
|---|---|---|---|
hasOne | User | Profile | One-to-one |
hasMany | User | Posts | One-to-many |
belongsTo | Post | User | Inverse |
belongsToMany | Post | Tags | Many-to-many (pivot) |
hasManyThrough | Country | Posts | Through Users |
morphMany | Post/Video | Comments | Polymorphic |
// ❌ N+1 Problem
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name; // Query per iteration!
}
// ✅ Eager Load
$posts = Post::with('author')->get();
foreach ($posts as $post) {
echo $post->author->name; // No extra queries
}
// ✅ Nested Eager Load
$posts = Post::with(['author', 'comments.user'])->get();
// ✅ Lazy Eager Load (after query)
$posts = Post::all();
$posts->load('author');
class PostFactory extends Factory
{
public function definition(): array
{
return [
'title' => fake()->sentence(),
'body' => fake()->paragraphs(3, true),
'user_id' => User::factory(),
'published_at' => null,
];
}
public function published(): static
{
return $this->state(fn (array $attrs) => [
'published_at' => now(),
]);
}
}
// Single
$post = Post::factory()->create();
// Multiple
$posts = Post::factory()->count(5)->create();
// With state
$post = Post::factory()->published()->create();
// With relationship
$post = Post::factory()
->has(Comment::factory()->count(3))
->create();
// Local scope
public function scopePublished(Builder $query): void
{
$query->whereNotNull('published_at');
}
public function scopeByAuthor(Builder $query, User $user): void
{
$query->where('user_id', $user->id);
}
// Usage
Post::published()->byAuthor($user)->get();
protected $casts = [
'metadata' => 'array',
'is_active' => 'boolean',
'published_at' => 'datetime',
'price' => 'decimal:2',
'status' => PostStatus::class, // Enum
];
// Select specific columns
User::select(['id', 'name', 'email'])->get();
// Use chunk for large datasets
Post::chunk(100, function ($posts) {
foreach ($posts as $post) {
// Process...
}
});
// Use cursor for memory efficiency
foreach (Post::cursor() as $post) {
// One at a time, low memory
}
$users = User::withCount('posts')->get();
// Access: $user->posts_count
Post::updateOrCreate(
['slug' => $slug],
['title' => $title, 'body' => $body]
);
$user = User::firstOrCreate(
['email' => $email],
['name' => $name]
);
// ❌ Avoid raw DB facade
DB::table('posts')->where('user_id', $userId)->get();
// ✅ Use Model::query()
Post::query()->where('user_id', $userId)->get();
Use
Model::query()for type hints and IDE support. Only useDB::for complex raw SQL that Eloquent can't express.
// ✅ Modern approach (Laravel 12+)
protected function casts(): array
{
return [
'metadata' => 'array',
'is_active' => 'boolean',
'published_at' => 'datetime',
'status' => PostStatus::class,
];
}
// ⚠️ Still works but less flexible
protected $casts = ['status' => PostStatus::class];
// ✅ Laravel 12 native - no packages needed
$users = User::with(['posts' => function ($query) {
$query->latest()->limit(5);
}])->get();
use Illuminate\Database\Eloquent\Casts\Attribute;
// ✅ Modern syntax
protected function fullName(): Attribute
{
return Attribute::make(
get: fn () => "{$this->first_name} {$this->last_name}",
set: fn (string $value) => [
'first_name' => ($parts = explode(' ', $value, 2))[0],
'last_name' => $parts[1] ?? '',
],
);
}
// ❌ Legacy syntax (still works)
public function getFullNameAttribute(): string
{
return "{$this->first_name} {$this->last_name}";
}