Eager loading in Laravel allows you to retrieve related models along with the main model to prevent the N+1 query problem. By default, when you eager load, it retrieves all columns of the related models. However, if you want to retrieve specific columns from the related models, you can use the select
method in your eager loading query.
Here’s an example of how to use eager loading with selected columns in Laravel:
$posts = App\Post::with(['comments' => function ($query) {
$query->select('post_id', 'body'); // Selecting only 'post_id' and 'body' columns from comments table
}])->get();
Here, we’re using the select method to specify which columns we want to retrieve from the comments table.