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

You have two possibilities:

  1. Change your expected result into something more compex, like this:
'item': {cost: 409, ...},
'likers': [{'id': 1, 'name': 'Brad Pitt'}, {...}, ...]
{ 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;

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.

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.

Sign in to participate in this thread!


Your banner here too?

amilajack amilajack Joined 19 Jul 2014


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

Your logo here?

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

© 2023 - All rights reserved.