Support the ongoing development of Laravel.io →
Requests Eloquent Views
Last updated 1 year ago.
0

You have two possibilities:

  1. Change your expected result into something more compex, like this:
[
{
'item': {cost: 409, ...},
'likers': [{'id': 1, 'name': 'Brad Pitt'}, {...}, ...]
},
{...next item with likers...}
]
  1. You're probably just returning a collection, wich makes a json response like so:
$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.

Last updated 1 year ago.
0

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.
}
Last updated 1 year ago.
0

Sign in to participate in this thread!

Eventy

Your banner here too?

amilajack amilajack Joined 19 Jul 2014

Moderators

We'd like to thank these amazing companies for supporting us

Your logo here?

Laravel.io

The Laravel portal for problem solving, knowledge sharing and community building.

© 2024 Laravel.io - All rights reserved.