I have a table called celebrities that has a many-to-many relationship to three other tables: collections, categories, and tags. I currently have my API set up to return the following:
[
{
"id": 1,
"display_name": "Joe Shmo",
"born": "1917-05-11",
"died": null,
"biography": "Some guy in a well-known TV show.",
"collections": [
{
"id": 1,
"name": "Featured Celebrity"
}
],
"categories": [
{
"id": 1,
"name": "Movies/TV"
}
],
"tags": []
},
{
"id": 2,
"display_name": "Jane Doe",
"born": "1914-05-11",
"died": "1993-10-30",
"biography": "She was famous for a show in the 80's.",
"collections": [
{
"id": 2,
"name": "Top Ten Celebrities"
}
],
"categories": [
{
"id": 1,
"name": "Movies/TV"
}
],
"tags": []
},
...
I'd like to return the JSON grouped by the name value from collections. Here's an example of what I want:
[
{
"Feature Celebrity": [
{
"id": 1,
"display_name": "Joe Shmo",
"born": "1917-05-11",
"died": null,
"biography": "Some guy in a well-known TV show.",
"categories": [
{
"id": 1,
"name": "Movies/TV"
}
],
"tags": []
}
]
},
{
"Top Ten Celebrities": [
{
"id": 2,
"display_name": "Jane Doe",
"born": "1993-05-11",
"died": null,
"biography": "A famouse beach volley ball person.",
"categories": [
{
"id": 2,
"name": "Sports"
}
],
"tags": []
},
...
]
}
]
As for my Laravel code, here is what I have setup.
Celebrity (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Celebrity extends Model
{
protected $hidden = ['pivot'];
public function categories()
{
return $this->belongsToMany('App\Category');
}
public function collections()
{
return $this->belongsToMany('App\Collection');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
}
Collection (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Collection extends Model
{
protected $hidden = ['pivot'];
public function celebrities()
{
return $this->belongsToMany('App\Celebrity');
}
}
Category (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Category extends Model
{
protected $hidden = ['pivot'];
}
Tag (model)
namespace App;
use Illuminate\Database\Eloquent\Model;
class Tag extends Model
{
protected $hidden = ['pivot'];
}
In my CelebrityController I have the following code that returns JSON in the format like I show in the first example:
public function list($born = null) {
if (!isset($born)) {
$born = date('m-d');
}
return Celebrity::with([
'collections:id,name',
'categories:id,name',
'tags:id,name',
])
->where('born', 'like', '%-' . $born . '%')
->get([
'id',
'display_name',
'born',
'died',
'biography',
]);
}
Here is an image of my tables and their relationships: Celebrity Tables
I'm very new to Laravel and Eloquent. I can't figure out how to get from the first JSON example to the second. Any help would be appreciated.