After 2+ years working with Laravel, I discovered these 5 Eloquent techniques that completely changed how I build applications. Number 3 will save you hours of debugging!
- Eager Loading vs Lazy Loading - The Performance Game Changer
// Don't do this (N+1 problem)
$users = User::all();
foreach($users as $user) {
echo $user->profile->name;
}
// Do this instead
$users = User::with('profile')->get();
- Local Scopes - Your Query Building Superpower
// In your Model
public function scopeActive($query) {
return $query->where('status', 'active');
}
// Usage
$activeUsers = User::active()->get();
- Accessors & Mutators - Clean Data Transformation
// Automatically format data
public function getFullNameAttribute() {
return $this->first_name . ' ' . $this->last_name;
}
- Relationship Tips You Probably Didn't Know
// Access related data without extra queries
$user = User::with('posts.tags')->find(1);
$user->posts->first()->tags;
- The Hidden Gem: tap() Helper Function
// Cleaner object manipulation
return tap($user, function($user) {
$user->update(['last_login' => now()]);
});
Top comments (0)