0
votes

i'm using laravel 7.30, I have a post model linked to user model with belongsTo relationship, I want to retrieve all posts with user property that contains only the name of the user for api purposes.

what i've tried so far.

public function index()
{
    return Post::with('user:id,name')->get();
}

but the result of this code is a nested object 'user' which has 2 fields id and name on each post, I only want a single field with posts fields called user which has the name only and not a nested object for api purposes.

I've made it using database query builder, but i'm looking for a way using Eloquent

Thanks in advance

1

1 Answers

1
votes

You can add this to your Post Model:

protected $appends = [
    "author_name"
];

public function getAuthorNameAttribute()
{
    return $this->user->name;
}

This will make sure the user's name is appended to the Post object every time it is being called.

Then from your controller, you can easily do this:

public function index()
{
    return Post::get();
}