Eager Loading with Selected Columns in Laravel

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();
Now we will only get the author's id, name rather than all visible columns. So there is also a hidden & nice way to do the same, you can get the same result as above by the following code too.
Blog::with('author:id,name')->get();
Remember one thing you will need to select relational columns or else it will not work, i.e. in this example if you remove `id` from selection it will not work.
If you have any queries or doubts about this topic please feel free to contact us. We will try to reach you.
Comments (0)

Generate Free SSL Certificate
- 90-Day Certificates
- SSL Monitoring
- Wildcard Certificates
- Multiple Domains
- Certificate Management
- Expiration Reminders
Popular Blogs
ServerAvatar
Multiple sites on a single VPS/VM/Server
Deploy PHP sites on cloud in minutes, simple as that!

Latest Blogs
No Comments Found.