Search code examples
laraveleloquentrelationshipeager-loading

How to get only selected column in a child related model?


I have two models, User and Post, where a User can have multiple Post models. In my application, I only want to retrieve the title column from the related Post model when querying for a User. Here is my current code:

class User extends Model
{
    public function posts()
    {
        return $this->hasMany(Post::class);
    }
}

class Post extends Model
{
    public function user()
    {
        return $this->belongsTo(User::class);
    }
}

Here is what I have tried to retrieve the title column for the related Post models:

$user = User::with('posts:title')-\>get();

However, this retrieves all the columns for the Post model. How can I modify my code to only retrieve the title column for the related Post models? Thank you!


Solution

  • try this

     $user = User::with(['posts' => function ($query) {
                          $query->select('title');
                  }])->get();