Eager Loading with Selected Columns in Laravel

Posted on

Let’s say we have a case where we have a blog and each blog has authors and we need all author’s name with each blog so what we are going to do is:

Blog::with(‘author’)->get()
Now, in this case, we only need the author’s name only rather than the full data of the author’s table right? so what we can do:

Blog::with([‘author’ => function($query) {
return $query->select([‘id’, ‘name’]);
}])->get();

https://techvblogs.com/blog/laravel-eager-loading-with-selected-columns

Leave a Reply

Your email address will not be published.