How to implement many-to-many relationships in LARvel 4 RESTful API

I would like to implement something similar to what was asked in this question in Laravel 4, where the player/ resource can have more than one team/ , and vice versa.

In an ideal world, I could request

players/1/teams

and return some JSON as follows:

 { 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 correlative.

Obviously, if I used Laravel views, I could just call $player->teams and everything will be fine, but this is for the JSON API, so everything should be in front.

I also need to be able to break down related results, although this is probably another question.

How can I do this with Laravel?

Thanks for any help!

+4
source share
2 answers

Laravel 4 added support for nested resource routes. They are quite pleasant and seem quite suitable for you.

Basically, besides your β€œdirect” resource controllers, you need to add routes for your nested resources. In this case, in addition to:

 Route::resource('players', 'PlayersController'); // players/# Route::resource('teams', 'TeamsController'); // teams/# 

... you will need:

 Route::resource('players.teams', 'PlayerTeamsController'); // players/#/teams/# Route::resource('teams.players', 'TeamPlayersController'); // teams/#/player/# 

Then, in your controllers, methods that usually receive one ID as a parameter will now receive two (the order is determined by your route):

 class PlayerTeamsController extends Controller { public function show($player_id, $team_id) { } } 

You can then use inheritance to avoid code redundancy between your controllers.

+3
source

Through the API, just enable the link and return the object (in laravel 4). L4 will automatically format the data for JSON output.

 return Player::with( [ 'teams' ] )->get(); 

This will give you pretty much exactly the format you need :)

+1
source

Source: https://habr.com/ru/post/1495750/


All Articles