Laravel Eager Loading: Fetch Specific Columns in Relationships Using with()

Learn 3 ways to optimize Laravel eager loading by fetching only specific columns using with(). Reduce query overhead and improve performance!

Laravel Eager Loading: Fetch Specific Columns in Relationships Using with() Image

Eager loading in Laravel (using with()) prevents the N+1 query problem, but did you know you can optimize it further by selecting only the columns you need? This improves memory usage and query speed.

3 Ways to Select Specific Columns Using with() function

Method 1: Simple Column Selection

$posts = Post::query()->latest()->with('author:id,name');
  • Most concise syntax
  • Works for simple cases where you just need specific columns
  • Requires the foreign key (typically id) to be included for the relationship to work

Method 2: Closure-Based Column Selection

$posts = Post::query()->latest()->with([
    'author' => function ($query) {
        $query->select('id', 'name');
    }
]);
  • More flexible approach
  • Allows additional query constraints
  • Can add other clauses like where, orderBy, etc.

Method 3: Defined in Model Relationship

// In your Post model
public function author()
{
    return $this->belongsTo(User::class, 'author_id')->select('id', 'name');
}
  • Most maintainable for frequently used column selections
  • Applies consistently wherever the relationship is used
  • Can be overridden in queries when needed

Important Notes:

  1. Always include the primary key (and foreign key if different) in your selected columns
  2. Method 3 affects all queries using this relationship, which may not always be desirable
  3. For complex relationship queries, Method 2 provides the most flexibility

Choose the method that best fits your specific use case and application architecture.

Happy Coding! 😊

Do you Like?