Tom Nolan
Tom Nolan

Reputation: 1957

How to return two one to many relationships in an API response with Laravel controller?

So, I have three models - Events, Groups and Individuals. I'm trying to create an API response that provides a list of groups AND the individuals in each group. I've been able to create a response that provides a list of the groups, but I'm not sure how to also PROPERLY include the individuals of each group.

I thought about just looping through each from the first response and making another query for each, but that seemed like overkill. So, the question is how can I include the Individuals for each Group within the response as well.

I have all three eloquent models defined as such:

Events:

public function groups()
{
    return $this->hasMany('App\Group');
}

Groups:

public function event()
{
    return $this->belongsTo('App\Event');
}
public function individuals()
{
    return $this->hasMany('App\Individual');
}

Individuals:

public function group()
{
    return $this->belongsTo('App\Group');
}

Then I have my route:

Route::get('/events/{id}/groups', 'EventsController@groups');

Then that controller has the function to return the list of groups:

public function groups($eventId)
{
    $event= Event::find($eventId);
    $groups= $event->groups()->paginate();

    return $groups;
}

Any help would be greatly appreciated. To clarify, I'd be looking for a response that looks something like:

{
    id: 1,
    group_name: 'Group Name',
    individuals: [ .. array of individuals .. ]
}

Or if someone could give feedback on a better or more standard way to do it, I'd be open to that as well.

Upvotes: 1

Views: 1007

Answers (2)

Alexey Mezenin
Alexey Mezenin

Reputation: 163758

Since you already know event ID, you can use Group model directly and load individuals by using with() method. This code will create just two queries and it's less verbose:

public function groups($eventId)
{
    return Group::where('event_id', $eventId)->with('individuals')->paginate(5);
}

Upvotes: 3

Hammerbot
Hammerbot

Reputation: 16334

You need to use Eager Loading with the with() method:

public function groups($eventId)
{
    $event= Event::find($eventId);
    $groups= $event->groups()->with('individuals')->paginate();

    return $groups;
}

Upvotes: 3

Related Questions