You have two possibilities:
[
{
'item': {cost: 409, ...},
'likers': [{'id': 1, 'name': 'Brad Pitt'}, {...}, ...]
},
{...next item with likers...}
]
$items = Item::with('likers')->get();
return $items;
Use the Response:json method instead. Pass an array as argument.
$array = array();
foreach(Item::with('likers')->get() as $item){
$itemArray = $item->toArray();
$itemArray['likers'] = $item->likers;//this should work even without toArray
$array[] = $itemArray;
}
Response::json($array);
Be carefull. If all keys in an array are integers, the Response::json result will be an array in json. If there is only one non integer key, the result will be a struct. You handle them differently in javascript.
You can very well use Eloquent relationship for this one.
Assuming you have a relationship likes
setup already. Just add this method to your Items model :
public function getUserLikeIdAttribute()
{
return $this->likers->lists('id');
}
And to get this on your json response, just add this to your Items model :
protected $appends = array('user_like_id');
Now your controller method is as simple as :
public function items()
{
return Items::with('likes')->take(10)->get(); // Implement the random logic.
}
Sign in to participate in this thread!
The Laravel portal for problem solving, knowledge sharing and community building.
The community