Saeed Vaziry
Saeed Vaziry

Reputation: 2355

Select specific column in laravel eloquent's with method

I am using laravel 5.6 and i want to get user posts with comments (only id field)

User Model

public function posts()
{
    return $this->hasMany('App\Post');
}

Post Model

public function user()
{
    return $this->belongsTo('App\User');
}

public function comments()
{
    return $this->hasMany('App\Comment');
}

Comment Model

public function post()
{
    return $this->belongsTo('App\Post');
}

In my controller i am using this code to get user posts with their comments

$posts = $request->user()->posts()->with(['comments' => function($query) {
    $query->select(['id']);
}]); 

But its not working...

When i comment $query->select(['id']); it works fine but returns Comment model all fields. I want to only select id field.

What i am missing here?

Upvotes: 3

Views: 4138

Answers (2)

Jonas Staudenmeir
Jonas Staudenmeir

Reputation: 25906

You also have to select the foreign key column (required for matching the results):

$posts = $request->user()->posts()->with('comments:id,post_id'); 

Upvotes: 2

webdevtr
webdevtr

Reputation: 480

If you want to only one column, you can use ->pluck('id')

https://laravel.com/docs/5.6/collections#method-pluck

Upvotes: -1

Related Questions