Eloquent simplifies database operations. Advanced relationships and query techniques unlock powerful capabilities. At ZIRA Software, mastering Eloquent optimizations improved application performance by 10x.
Polymorphic Relationships
One-to-many polymorphic:
// Commentable interface
class Post extends Model {
public function comments() {
return $this->morphMany(Comment::class, 'commentable');
}
}
class Video extends Model {
public function comments() {
return $this->morphMany(Comment::class, 'commentable');
}
}
class Comment extends Model {
public function commentable() {
return $this->morphTo();
}
}
// Usage
$post = Post::find(1);
$post->comments; // All comments for this post
$comment = Comment::find(1);
$comment->commentable; // Post or Video
Many-to-many polymorphic:
class Tag extends Model {
public function posts() {
return $this->morphedByMany(Post::class, 'taggable');
}
public function videos() {
return $this->morphedByMany(Video::class, 'taggable');
}
}
// Usage
$tag = Tag::find(1);
$tag->posts; // All posts with this tag
$tag->videos; // All videos with this tag
Subquery Selects
// Get latest post for each user
$users = User::addSelect(['latest_post_title' => Post::select('title')
->whereColumn('user_id', 'users.id')
->latest()
->limit(1)
])->get();
// Order by subquery
$users = User::orderByDesc(
Post::select('created_at')
->whereColumn('user_id', 'users.id')
->latest()
->limit(1)
)->get();
Lazy Eager Loading
$posts = Post::all();
// Later realize you need comments
$posts->load('comments');
// Load with constraints
$posts->load(['comments' => function ($query) {
$query->where('approved', true);
}]);
// Load count
$posts->loadCount('comments');
Query Scopes
Local scopes:
class Post extends Model {
public function scopePublished($query) {
return $query->where('published', true);
}
public function scopePopular($query) {
return $query->where('views', '>', 1000);
}
}
// Usage
Post::published()->popular()->get();
Advanced Where Clauses
// Subquery where
User::whereIn('id', function ($query) {
$query->select('user_id')
->from('orders')
->where('total', '>', 1000);
})->get();
// JSON where
Product::where('metadata->color', 'blue')->get();
// Date where
Order::whereDate('created_at', '2021-03-15')->get();
Order::whereMonth('created_at', 3)->get();
Conclusion
Advanced Eloquent techniques solve complex data requirements elegantly. Master these patterns for optimal Laravel development.
Need database optimization? Contact ZIRA Software for performance consultation.