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

Learn how to optimize Laravel eager loading by fetching specific columns in relationships using load(). Improve performance and reduce query load in your Laravel application.

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

While with() eager loads relationships upfront, load() lazy-loads them after the parent query. Here’s how to make load() efficient by fetching only specific columns.

How to Use load() with Column Selection

Method:1 Basic Column Selection

public function show(Post $post)
{
    return $post->load('author:id,name');
}
  • Works identically to with() but after the initial query.

Method:2 Advanced Filtering with Closures

$posts->load(['author' => function ($query) {
    $query->select('id', 'name')->where('active', true);
}]);

Use Case: Conditional loading (e.g., only active authors).

Performance Tip

Combine load() with select() on the parent model:

$posts = Post::select('id', 'title')->get();
$posts->load('author:id,name'); // Only loads needed columns!

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

Happy Coding! 😊

Do you Like?