1 year ago

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

Posted 1 year 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 = [

$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.