i'm working on a function that returns info related to two ids. And i would like to attach those ids to the response right after the success message. Here is my code:
The Controller function that make a call to another one in the Repository (that is working fine)
public function getCampaignEstablishments($lang, $campaignId, $companyId)
{
$establishments = $this->repository->allEstablishments($campaignId, $companyId);
return CampaignEstablishments::collection($establishments);
}
The Resource function that filters the data (for testing im displaying all of it)
class CampaignEstablishments extends PotatoesResource
{
const SINGLE_KEY = 'establishment';
const COLLECTION_KEY = 'establishments';
public function toArray($request)
{
return parent::toArray($request);
}
}
And this is the imported collection Resource
public static function collection($collection)
{
$subclass = get_called_class();
return self::baseResource(
$subclass::COLLECTION_KEY,
parent::collection($collection)
);
}
public static function baseResource($key, $value)
{
return [
'success' => true,
$key => $value
];
}
Currently i'm getting this response
{
"success": true,
"establishments": [
{
/*Data of an establishment*/
},
{
/*Data of an establishment*/
},
{
/*Data of an establishment*/
}
]
}
And this is the response i would like to get
{
"success": true,
"campaign_id": /*the id passed in $campaignId*/
"company_id": /*the id passed in $companyId*/
"establishments": [
{
/*Data of an establishment*/
},
{
/*Data of an establishment*/
},
{
/*Data of an establishment*/
}
]
}
I've tried a lot of different ways and got a lot of different structures but not this one in particular. Is it possible to achieve this?
You just need to return it in an associative array:
return [
"success" => true,
"campaign_id" => $campaignId,
"company_id" => $companyId,
"establishments" => CampaignEstablishments::collection($establishments),
];
UPDATED: Then you need to do this:
$establishments = CampaignEstablishments::collection($establishments);
$establishments['campaign_id'] = $campaignId;
$establishments['company_id'] = $companyId;
return $establishments;