1

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();
2
  • What is the output of Building::with('room')->get();? Commented Feb 11, 2015 at 0:31
  • The JSON above is an example of what I get with that. Commented Feb 11, 2015 at 8:15

1 Answer 1

1

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
}
Sign up to request clarification or add additional context in comments.

1 Comment

That worked perfectly. I hadn't considered using hidden. Thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.