Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

gustav1105's avatar

Retrieving aggregated results from many eloquent models for api request

My question concerns the output that is returned from a query. Lets say that I am querying four different tables in one api request and I send through the user id as a wildcard.

So putting the query into words, it sounds like this.

I get the user id from the request and find the user in the users tabel, then using the relationship hasMany properties I get the properties where the user is the owner with->( references) and for each reference query a advertiser table to obtain the specific advertiser.

then return.

So the problem is a am getting a bit of a mess returned! All the relevant information is available, but I get all the timestamps and other information that is not particularly important to this specific request. The return lets call it output, is an object and this objects is quite bloated, where there seems to be nested objects inside nested objects (which is to be expected) but some of the nested objects seems only to be a holder for a nested object that has its own nested objects.

So not to get to off-track here, I would like to know,

What procedures, or method or methodology or tutorials will be a wise choice when working with data like this, for instance how to serialize or transform and how to create the model relations?

In a perfect world I would like to return output

user:{}
properties:{
1:object{
(key)property_id:(value)property_number
references:{
1:object{
(key)reference_id:(value)reference_number
advertiser{
(key)advertiser_id:(value)advertiser_name
}
}
2:object{}
3:object{}
4:object{}
}
}
2:object{}
3:object{}

}

Well something like the above.

So please to all the guys that has been working with api's and have good practical ideas on how I might chronologically work through the problem please advise?

Thanks.

0 likes
1 reply
Borisu's avatar
Borisu
Best Answer
Level 37

Hi,

some ways you can start doing it: Use pluck to just display data you want

$model->relationship()->get()-pluck('field1', 'field2')

Then you can also limit the output from your model by using:

protected $hidden = ['column1', 'column2'];

The hidden property will hide columns from all your requests tho, so be thoughtful when using it. Or of course whitelist some values with visible.

Aaand finally you can append values to your json responses, for a easier access, avoiding complex object in an object stuff.

protected $appends = ['accessorName'];

https://laravel.com/docs/5.4/collections#method-pluck

https://laravel.com/docs/5.4/eloquent-serialization#hiding-attributes-from-json

https://laravel.com/docs/5.4/eloquent-serialization#appending-values-to-json

1 like

Please or to participate in this conversation.