Suba
Suba

Reputation: 199

Getting specific columns from Laravel Eloquent

I've been beating myself up with this and can't seem to be able to get my JSON to only display the title and description of the rooms should they be live. I have tried using return $this->hasMany('Room')->select(array('id', 'title', 'description')); but it returns nothing at all for rooms.

Can anyone help? I'm sure this must be very simple to achieve as I understood Laravel Eloquent to be simplistic for this kind of task.

JSON

[
    {
        id: 1,
        building_title: "Drum Castle"
        room: [
            {
                id: 1,
                building_id: 7,
                title: "Snooker Room",
                description: "Full Description",
                live: 1
            }
        ]
    }
]

Building Model

public function room()
{
    return $this->hasMany('Room');
}

Room Model

public function building()
{
   return $this->belongsTo('Building', 'building_id');
}

Controller

$buildings = Building::with('room')->get();

Upvotes: 1

Views: 376

Answers (1)

patricus
patricus

Reputation: 62248

Your attempt at restricting the fields on the relationship failed because you didn't select the building_id field. If you don't get this field, Laravel has no idea on which rooms belong to which buildings (think about eager loaded relationships).

One method to do what you want is to override the toArray() method (which is called by toJson()), on either the Building or the Room.

Another option is to set the hidden/visible attributes on your Room model. The attributes will govern which fields are hidden/visible when converting to an array.

class Room extends Eloquent {
    protected $hidden = array('building_id', 'live');
    // or
    protected $visible = array('id', 'title', 'description');

    // rest of class
}

Upvotes: 1

Related Questions