louisl

Is it possible to filter fields in a collection but still keep the collection structure?

Posted 4 days ago by louisl

I'm trying to reduce the payload for an api call so I'd like to thin out the results somehow to just the fields I need

// Example fields.
$fields = [
    'location.name',
    'location.address.latitude',
    'location.address.longitude'
];

$includes = ['address'];

$result = Location::with($includes)->get();

From the result I actually only want the $fields specified but I do want to keep the structure. The idea is that this is reusable, so $includes and $fields could vary depending what's set in the api request.

$wantedResult = [
    'name' => 'abc',
    'address' => [
        'latitude' => 123,
        'longitude' => 123
    ]
];

Please sign in or create an account to participate in this conversation.

Reply to

Use Markdown with GitHub-flavored code blocks.