kayex
kayex

Reputation: 119

Laravel 5.4 accessor with relationship returns related model

I probably missed something really obvious, but have had no luck thus far. I have two related models, Messages and Users. I'm trying to append only the 'username' of the user who created the message when retrieving all messages. I am getting a fully serialized related user model however. I understand I could $hidden in my User model, but would like to avoid that.

In my Messages model, I've created a relationship

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

Then I've added

protected $appends = ['username'];

Along with a custom attribute

public function getUsernameAttribute($value)
{
    $username = null;
    if ($this->createdBy){
        $username = $this->createdBy->username;
    }
    return $username;
}

When I'm getting messages through another relationship such as

return $channel->messages()->orderBy('id','desc')->get();

I end up with the following response:

[{"id":97,"to_id":"12345","message":"This is the message content","created_at":"2017-02-25 08:58:22","created_by":{"id":1,"email":"REDACTED","name":"REDACTED","username":"myusername","created_at":"2016-09-26 16:00:00","created_by":null,"updated_at":"2017-02-20 00:33:06","updated_by":null},"updated_at":"2017-02-25 08:58:22","updated_by":null,"deleted_at":null,"username":"myusername"}, ...

What am I doing wrong, or is there a better way to accomplish what I'm trying to do?

Upvotes: 2

Views: 663

Answers (1)

kayex
kayex

Reputation: 119

I didn't realize I was able to hide the relationship in the original model. I ended up hiding the createdBy relationship in the Messages model.

protected $hidden = [
   'createdBy'
];

Upvotes: 2

Related Questions