Column selection in eager loading

Submitted by stidges - 10 years ago

I recently figured out that you can specify the columns that you want to select from an eager loaded relationship in Eloquent. I thought others might find this useful as I couldn't find much about this online!

// Example: Post model belongs to an Author. We only want the name of the author.

$posts = Post::with(array('author' => function($query)
{
    // Notice that you add either the primary key or the
    // foreign key to the field list, or else Laravel
    // won't be able to link the models together!
    $query->addSelect(array('id', 'name'));
}))->get();

// To further explain the note I place within the closure, let's do it the other way around as well.

// Example: We only want the title of the posts.
$authors = Author::with(array('posts' => function($query) 
{
    // Notice the addition of the author_id field!
    $query->addSelect(array('title', 'author_id'));
}))->get();