Wednesday, 7 August 2013

How do implement many-to-many relationships in a Laravel 4 RESTful API

How do implement many-to-many relationships in a Laravel 4 RESTful API

I'd like to implement something similar to what's asked in this question
in Laravel 4, where a player/ resource can have more than one team/, and
vice-versa.
In an ideal world I would be able to query
players/1/teams
and get back some JSON like this:
{ player: {
id: 1, name: 'Bob', sport: 'Curling', teams: [
{ id: 1, name: 'Northern Curling Soc.', age: 2},
{ id:2, name: 'Southern Curling Soc.', age: 4 }
]
}
or
teams/{id}/players and get the correlative.
Obviously if I were using Laravel's views I could simply call
$player->teams and all would be well, but this is for a JSON API so it all
needs to be up front.
I also need to be able to paginate the related results, although this is
probably a different question.
How can I do this with Laravel?
Thanks for any help!

No comments:

Post a Comment