Q:

Eloquent relationship: return just one value not entire row

In my laravel project I built a comment section and want to display the names of the people commenting beside their comment.
Initially I have just the userID, so I built a relationship (hasOne) linking the comment table (comment &  authorID) to the users table (id (authorID) & username)
Comment.php (model) is:
[..]
        public function author()
        {
            return $this->hasOne(User::class, 'id', 'Author');
        }

The User.php model is:
<?php

[..]
        public function author()
        {
            return $this->hasMany(Comment::class, 'Author', 'id');
        }

In the controller I get the data with:
$comments= Comments::where('LinkID', (string) $id)->with('author')->orderBy('updated_at', 'ASC')->get()->all();

This works but it gives me the entire row of the user per comment. For security reasons I just want to return the 'name' field of the row (username) without the rest (email, timestamps etc.).
How can I achieve this?

A:

please try:
$comments= Comments::where('LinkID', (string) $id)->with(['author' => function ($q) {
                $q = $q->select('name', 'id');
                return $q;
}
])->orderBy('updated_at', 'ASC')->get()->all();

or another way:
$comments= Comments::where('LinkID', (string) $id)->with('author:id,name')->orderBy('updated_at', 'ASC')->get()->all();

see eager loading (section Eager Loading Specific Columns)
https://laravel.com/docs/7.x/eloquent-relationships#eager-loading
note that including 'id' is necessary because it 's responsible for the relation  

