Select specific column in laravel eloquent's with method

Saeed Vaziry

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?

Jonas Staudenmeir

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

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

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Laravel Auditing - How To Get Specific Column Using Eloquent Model Method

Laravel Eloquent search JSON array for a specific column's value

Select specific column only if matches the ID in Eloquent

How to select specific columns in laravel eloquent

Laravel eloquent select data only specific term

Laravel Eloquent select query for payment method used

Laravel eloquent using null as column value on select?

Laravel (Eloquent) equivalent of Mongoose's populate() method

Laravel Eloquent Sum of relation's column

Laravel select specific columns with Eloquent while eager loading

Laravel 5 Eloquent scope join and select specific columns

Laravel Eloquent with() selecting specific column doesn't return results

laravel - eloquent - get sum of related model specific column

Laravel : Select email column based on user role (Eloquent)

Laravel - Add custom column in select with Eloquent query buider

Adding a count column for a filtered relationship to a select with a subquery in Laravel Eloquent

Laravel Eloquent: How to retrieve array of values for each column in select?

Laravel hasMany relationship select specific column issue

Laravel Eloquent wherePivot method returns column 'pivot' not found

laravel eloquent select dynamic

Select in eloquent join laravel

Laravel Eloquent Select Issue

Laravel 5.4 Eloquent select with

Laravel - Nested select (Eloquent)

Laravel Custom Eloquent Method

Laravel eloquent skip method

How to use break or continue with Laravel Eloquent Collection's each method?

Laravel 5: Alternative for Eloquent's 'orWhere' method for querying collections

Laravel - What's the benefit of calling query() method on an Eloquent model