Laravel Eloquent ORM
Agent Workflow (MANDATORY)
Before ANY implementation, use TeamCreate to spawn 3 agents:
- fuse-ai-pilot:explore-codebase - Check existing models, relationships
- fuse-ai-pilot:research-expert - Verify latest Eloquent docs via Context7
- mcp__context7__query-docs - Query specific patterns (casts, scopes)
After implementation, run fuse-ai-pilot:sniper for validation.
Overview
Eloquent is Laravel's ActiveRecord ORM implementation. Models represent database tables and provide a fluent interface for queries.
| Feature |
Purpose |
| Models |
Table representation with attributes |
| Relationships |
Define connections between models |
| Query Scopes |
Reusable query constraints |
| Casts |
Attribute type conversion |
| Events/Observers |
React to model lifecycle |
| Factories |
Generate test data |
Critical Rules
- Always eager load relationships - Prevent N+1 queries
- Use scopes for reusable queries - Don't repeat WHERE clauses
- Cast attributes properly - Type safety for dates, arrays, enums
- No business logic in models - Keep models slim
- Use factories for testing - Never hardcode test data
Decision Guide
Relationship Type
What's the cardinality?
├── One-to-One → hasOne / belongsTo
├── One-to-Many → hasMany / belongsTo
├── Many-to-Many → belongsToMany (pivot table)
├── Through another → hasOneThrough / hasManyThrough
└── Polymorphic?
├── One-to-One → morphOne / morphTo
├── One-to-Many → morphMany / morphTo
└── Many-to-Many → morphToMany / morphedByMany
Performance Issue
What's the problem?
├── Too many queries → Eager loading (with)
├── Memory exhaustion → chunk() or cursor()
├── Slow queries → Add indexes, select columns
├── Repeated queries → Cache results
└── Large inserts → Batch operations
Reference Guide
Concepts (WHY & Architecture)
| Topic |
Reference |
When to Consult |
| Models |
models.md |
Model config, fillable, conventions |
| Basic Relations |
relationships-basic.md |
HasOne, HasMany, BelongsTo |
| Many-to-Many |
relationships-many-to-many.md |
Pivot tables, attach/sync |
| Advanced Relations |
relationships-advanced.md |
Through, dynamic relations |
| Polymorphic |
relationships-polymorphic.md |
MorphTo, MorphMany |
| Eager Loading |
eager-loading.md |
N+1 prevention, with() |
| Scopes |
scopes.md |
Local, global, dynamic |
| Casts |
casts.md |
Type casting, custom casts |
| Accessors/Mutators |
accessors-mutators.md |
Attribute transformation |
| Events/Observers |
events-observers.md |
Lifecycle hooks |
| Soft Deletes |
soft-deletes.md |
Recoverable deletion |
| Collections |
collections.md |
Eloquent collection methods |
| Serialization |
serialization.md |
toArray, toJson, hidden |
| Factories |
factories.md |
Test data generation |
| Performance |
performance.md |
Optimization techniques |
| API Resources |
resources.md |
JSON transformation |
| Transactions |
transactions.md |
Atomic operations, rollback |
| Pagination |
pagination.md |
paginate, cursor, simplePaginate |
| Aggregates |
aggregates.md |
count, sum, withCount, exists |
| Batch Operations |
batch-operations.md |
insert, upsert, mass update |
| Query Debugging |
query-debugging.md |
toSql, dd, DB::listen |
Templates (Complete Code)
| Template |
When to Use |
| ModelBasic.php.md |
Standard model with scopes |
| ModelRelationships.php.md |
All relationship types |
| ModelCasts.php.md |
Casts and accessors |
| Observer.php.md |
Complete observer |
| Factory.php.md |
Factory with states |
| Resource.php.md |
API resource |
| EagerLoadingExamples.php.md |
N+1 prevention |
Quick Reference
Basic Model
class Post extends Model
{
protected $fillable = ['title', 'content', 'author_id'];
protected function casts(): array
{
return [
'published_at' => 'datetime',
'metadata' => 'array',
];
}
public function author(): BelongsTo
{
return $this->belongsTo(User::class);
}
}
Eager Loading
// ✅ Good - 2 queries
$posts = Post::with('author')->get();
// ❌ Bad - N+1 queries
$posts = Post::all();
foreach ($posts as $post) {
echo $post->author->name;
}
Query Scopes
#[Scope]
protected function published(Builder $query): void
{
$query->whereNotNull('published_at');
}
// Usage: Post::published()->get();
Best Practices
DO
- Use
$fillable for mass assignment protection
- Eager load relationships with
with()
- Use scopes for reusable query logic
- Cast dates, arrays, and enums
- Use factories in tests
DON'T
- Put business logic in models
- Lazy load in loops (N+1)
- Use
$guarded = [] in production
- Query in accessors/mutators
- Forget foreign keys in
with() columns
1---2name: laravel-eloquent-33description: Complete Eloquent ORM - models, relationships, queries, casts, observers, factories. Use when working with database models.4metadata:5 source: https://skillmd.com/skills/fusengine/laravel-eloquent-36---78# Laravel Eloquent ORM910## Agent Workflow (MANDATORY)1112Before ANY implementation, use `TeamCreate` to spawn 3 agents:13141. **fuse-ai-pilot:explore-codebase** - Check existing models, relationships152. **fuse-ai-pilot:research-expert** - Verify latest Eloquent docs via Context7163. **mcp__context7__query-docs** - Query specific patterns (casts, scopes)1718After implementation, run **fuse-ai-pilot:sniper** for validation.1920---2122## Overview2324Eloquent is Laravel's ActiveRecord ORM implementation. Models represent database tables and provide a fluent interface for queries.2526| Feature | Purpose |27|---------|---------|28| **Models** | Table representation with attributes |29| **Relationships** | Define connections between models |30| **Query Scopes** | Reusable query constraints |31| **Casts** | Attribute type conversion |32| **Events/Observers** | React to model lifecycle |33| **Factories** | Generate test data |3435---3637## Critical Rules38391. **Always eager load relationships** - Prevent N+1 queries402. **Use scopes for reusable queries** - Don't repeat WHERE clauses413. **Cast attributes properly** - Type safety for dates, arrays, enums424. **No business logic in models** - Keep models slim435. **Use factories for testing** - Never hardcode test data4445---4647## Decision Guide4849### Relationship Type5051```52What's the cardinality?53├── One-to-One → hasOne / belongsTo54├── One-to-Many → hasMany / belongsTo55├── Many-to-Many → belongsToMany (pivot table)56├── Through another → hasOneThrough / hasManyThrough57└── Polymorphic?58 ├── One-to-One → morphOne / morphTo59 ├── One-to-Many → morphMany / morphTo60 └── Many-to-Many → morphToMany / morphedByMany61```6263### Performance Issue6465```66What's the problem?67├── Too many queries → Eager loading (with)68├── Memory exhaustion → chunk() or cursor()69├── Slow queries → Add indexes, select columns70├── Repeated queries → Cache results71└── Large inserts → Batch operations72```7374---7576## Reference Guide7778### Concepts (WHY & Architecture)7980| Topic | Reference | When to Consult |81|-------|-----------|-----------------|82| **Models** | [models.md](references/models.md) | Model config, fillable, conventions |83| **Basic Relations** | [relationships-basic.md](references/relationships-basic.md) | HasOne, HasMany, BelongsTo |84| **Many-to-Many** | [relationships-many-to-many.md](references/relationships-many-to-many.md) | Pivot tables, attach/sync |85| **Advanced Relations** | [relationships-advanced.md](references/relationships-advanced.md) | Through, dynamic relations |86| **Polymorphic** | [relationships-polymorphic.md](references/relationships-polymorphic.md) | MorphTo, MorphMany |87| **Eager Loading** | [eager-loading.md](references/eager-loading.md) | N+1 prevention, with() |88| **Scopes** | [scopes.md](references/scopes.md) | Local, global, dynamic |89| **Casts** | [casts.md](references/casts.md) | Type casting, custom casts |90| **Accessors/Mutators** | [accessors-mutators.md](references/accessors-mutators.md) | Attribute transformation |91| **Events/Observers** | [events-observers.md](references/events-observers.md) | Lifecycle hooks |92| **Soft Deletes** | [soft-deletes.md](references/soft-deletes.md) | Recoverable deletion |93| **Collections** | [collections.md](references/collections.md) | Eloquent collection methods |94| **Serialization** | [serialization.md](references/serialization.md) | toArray, toJson, hidden |95| **Factories** | [factories.md](references/factories.md) | Test data generation |96| **Performance** | [performance.md](references/performance.md) | Optimization techniques |97| **API Resources** | [resources.md](references/resources.md) | JSON transformation |98| **Transactions** | [transactions.md](references/transactions.md) | Atomic operations, rollback |99| **Pagination** | [pagination.md](references/pagination.md) | paginate, cursor, simplePaginate |100| **Aggregates** | [aggregates.md](references/aggregates.md) | count, sum, withCount, exists |101| **Batch Operations** | [batch-operations.md](references/batch-operations.md) | insert, upsert, mass update |102| **Query Debugging** | [query-debugging.md](references/query-debugging.md) | toSql, dd, DB::listen |103104### Templates (Complete Code)105106| Template | When to Use |107|----------|-------------|108| [ModelBasic.php.md](references/templates/ModelBasic.php.md) | Standard model with scopes |109| [ModelRelationships.php.md](references/templates/ModelRelationships.php.md) | All relationship types |110| [ModelCasts.php.md](references/templates/ModelCasts.php.md) | Casts and accessors |111| [Observer.php.md](references/templates/Observer.php.md) | Complete observer |112| [Factory.php.md](references/templates/Factory.php.md) | Factory with states |113| [Resource.php.md](references/templates/Resource.php.md) | API resource |114| [EagerLoadingExamples.php.md](references/templates/EagerLoadingExamples.php.md) | N+1 prevention |115116---117118## Quick Reference119120### Basic Model121122```php123class Post extends Model124{125 protected $fillable = ['title', 'content', 'author_id'];126127 protected function casts(): array128 {129 return [130 'published_at' => 'datetime',131 'metadata' => 'array',132 ];133 }134135 public function author(): BelongsTo136 {137 return $this->belongsTo(User::class);138 }139}140```141142### Eager Loading143144```php145// ✅ Good - 2 queries146$posts = Post::with('author')->get();147148// ❌ Bad - N+1 queries149$posts = Post::all();150foreach ($posts as $post) {151 echo $post->author->name;152}153```154155### Query Scopes156157```php158#[Scope]159protected function published(Builder $query): void160{161 $query->whereNotNull('published_at');162}163164// Usage: Post::published()->get();165```166167---168169## Best Practices170171### DO172- Use `$fillable` for mass assignment protection173- Eager load relationships with `with()`174- Use scopes for reusable query logic175- Cast dates, arrays, and enums176- Use factories in tests177178### DON'T179- Put business logic in models180- Lazy load in loops (N+1)181- Use `$guarded = []` in production182- Query in accessors/mutators183- Forget foreign keys in `with()` columns