Get Specific Columns Using “With()” Function in Laravel Eloquent Get Specific Columns Using “With()” Function in Laravel Eloquent laravel laravel

Get Specific Columns Using “With()” Function in Laravel Eloquent


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(array('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.*


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 andany relevant foreign key columns in the list of columns you wish toretrieve.

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.


For loading models with specific column, though not eager loading, you could:

In your Post model

public function user(){    return $this->belongsTo('User')->select(['id', 'username']);}

Original credit goes to Laravel Eager Loading - Load only specific columns