Search code examples
laravellaravel-3

Output entities with relationships in json


I have a device entity which has one-to-many relationship with picture entity. Like one device has many pictures. How can I output in JSON all device properties plus array of pictures?

When I try:

dd(Device::find(1)->pictures);

I get array of laravel objects with some additional information. I tried to do it in some ways but didn't managed to get just an array of simple picture objects (or array of arrays)

Although this works:

foreach (Device::find(1)->pictures as $picture) {
    $data['pictures']['path'] = $picture->path;
}
dd($data['pictures']);

It seems weird to form array that way

Basically I need to output json with arrays of one-to-many objects, like pictures and some other. So I'll get something like:

["name": "myDevice", "price": "15", "pictures": [...], "another": [...]]

I am using laravel 3


Solution

  • Are you using Laravel 3? In that case this should do the trick:

    return Response::eloquent(Device::with('pictures')->find(1));
    

    If your are using Response::eloquent the content-type is also automatically set to application/json.

    Edit: if you want only certain fields to return, you could use Response::json(Device::with('pictures')->lists('name', 'id')); to return an array just of that values already JSONified.