Eager Loading with Selected Columns in Laravel - TechvBlogs

Eager Loading with Selected Columns in Laravel

Eager Loading is a part of laravel relationship and it is the best. But sometimes we just need to get specific columns from the relation model.


Suresh Ramani - Author - TechvBlogs
Suresh Ramani
 

3 years ago

TechvBlogs - Google News

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 (1)

vishal vishal 4 months ago

#awesome_blog

Comment


Note: All Input Fields are required.