Get Specific Columns Using “With()” Function in Laravel Eloquent
You can do it like this since Laravel 5.5:
Post::with('user:id,username')->get();
Care for the id
field and foreign keys
as stated in the docs:
When using this feature, you should always include the id column and any relevant foreign key columns in the list of columns you wish to retrieve.
For example, if the user belongs to a team and has a team_id
as a foreign key column, then $post->user->team
is empty if you don't specifiy team_id
Post::with('user:id,username,team_id')->get();
Also, if the user belongs to the post (i.e. there is a column post_id
in the users
table), then you need to specify it like this:
Post::with('user:id,username,post_id')->get();
Otherwise $post->user
will be empty.
Well I found the solution. It can be done one by passing a closure
function in with()
as second index of array like
Post::query()
->with(['user' => function ($query) {
$query->select('id', 'username');
}])
->get()
It will only select id
and username
from other table. I hope this will help others.
Remember that the primary key (id in this case) needs to be the first param in the
$query->select()
to actually retrieve the necessary results.*