Eager Loading with Selected Columns in Laravel

  Laravel Published:  1 year ago
Eager Loading with Selected Columns in Laravel - TechvBlogs

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)

No Comments Found.