V-K
V-K

Reputation: 1347

Laravel hasOne get only one field instead of object

There two models user and also address, which contains country, city and etc. I need to get a list of users with the city, not with the whole address. Relation is oneToOne. The only thing I can get, using select['user_id', 'city']:

{
  "id": 1,
  "name": "John",
  "city": {
  "user_id": 3,
  "city": "Paris"
},

but I need:

{
  "id": 1,
  "name": "John",
  "city": "Paris"
}

Of course, I can use a loop and do something like $user->city = $user->address->city but maybe there is a better way to solve this problem. Laravel 5.4

Upvotes: 0

Views: 1099

Answers (1)

TsaiKoga
TsaiKoga

Reputation: 13394

You can use Accessor,

And append the attribute to json appending-values-to-json:

In your User model:

    protected $appends = ['city'];

    public function getCityAttribute()
    {
        return $this->city->city;
    }

Test it like this:

User::with('city')->get()->toJson();
// It will return:
// [{"id": 1, "name": "John", "city": "Paris", "city" : {"user_id": 3, "city": "Paris"}}, {...}]

Upvotes: 2

Related Questions