DEV Community

Hussein Code
Hussein Code

Posted on

5 Laravel Eloquent Secrets That Will Make You a Better Developer

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();
Enter fullscreen mode Exit fullscreen mode
  • Local Scopes - Your Query Building Superpower
// In your Model
public function scopeActive($query) {
    return $query->where('status', 'active');
}

// Usage
$activeUsers = User::active()->get();
Enter fullscreen mode Exit fullscreen mode
  • Accessors & Mutators - Clean Data Transformation
// Automatically format data
public function getFullNameAttribute() {
    return $this->first_name . ' ' . $this->last_name;
}
Enter fullscreen mode Exit fullscreen mode
  • Relationship Tips You Probably Didn't Know
// Access related data without extra queries
$user = User::with('posts.tags')->find(1);
$user->posts->first()->tags;
Enter fullscreen mode Exit fullscreen mode
  • The Hidden Gem: tap() Helper Function
// Cleaner object manipulation
return tap($user, function($user) {
    $user->update(['last_login' => now()]);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)