UPD: Solved. I Guess (check below)
I'm trying to group my API response by specific column with Laravel Resources
Like this
{
"data":{
"1":[ <=== (!!) To have this groups
{
"id":63,
"eve_id":95924195,
"name":"John",
"group":1, <== (!!!) from this column
"is_active":1,
"is_editable":1,
"created_at":"2018-11-08 05:26:20",
"updated_at":"2018-11-08 05:26:20"
},
{
"id":64,
"eve_id":95824961,
"name":"Doe",
"group":1,
"is_active":1,
"is_editable":1,
"created_at":"2018-11-08 05:41:10",
"updated_at":"2018-11-08 05:41:10"
}
]
}
}
My resource instance
class SomeResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'group' => $this->group,
'is_active' => $this->is_active,
'is_editable' => $this->is_editable,
'created_at' => (string) $this->created_at,
];
}
}
my collection instance:
class SomeCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\SomeResource';
public function toArray($request)
{
return [
'data' => $this->collection,
];
}
}
Using a basic eloquent method
Some::where('is_active', '1')->get()->groupBy('group');
return ['entries' => $entries];
can`t solve a problem at least if I somehow can pass these entries and iterate them at ResourceCollection
Thanks.
UPD: Okay, the issue was solved by creating new resource instance SomeGroupCollection and grouping was from the basic eloquent method
$entries = Some::where('is_active', '1')->get()->groupBy('group');
return new SomeGroupCollection($entries);
SomeGroupCollection
class SomeGroupCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\SomeCollection';
public function toArray($request)
{
return [
'entries' => $this->collection
];
}
}
SomeCollection
class SomeCollection extends ResourceCollection
{
public $collects = 'App\Http\Resources\SomeResource';
public function toArray($request)
{
return [
$this->collection,
];
}
}
SomeResource
class SomeResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'name' => $this->name,
'group' => $this->group,
'is_active' => $this->is_active,
'is_editable' => $this->is_editable,
'created_at' => (string) $this->created_at,
];
}
}