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

random@94's avatar

how to use flatten() in eloquent query ?

how to use flatten() in eloquent query ? and convert flattened data to 'toArray()'.

0 likes
10 replies
tisuchi's avatar

Have you checked this example in documentation?

$collection = collect([
    'Apple' => [
        ['name' => 'iPhone 6S', 'brand' => 'Apple'],
    ],
    'Samsung' => [
        ['name' => 'Galaxy S7', 'brand' => 'Samsung']
    ],
]);

$products = $collection->flatten(1);

$products->values()->all();

/*
    [
        ['name' => 'iPhone 6S', 'brand' => 'Apple'],
        ['name' => 'Galaxy S7', 'brand' => 'Samsung'],
    ]
*/

https://laravel.com/docs/5.5/collections#method-flatten

1 like
random@94's avatar

it give me a error "Call to undefined method Illuminate\Database\Query\Builder::flatten()"

And my code is

$query = self::select("bill_approval.*", \DB::raw("CONCAT('".env('AWS_PATH')."', bill_approval.bill_image) as bill_image")) ->with(['user:user_id,sso_username', 'category']) ->where('bill_approval.vendor_id', $vendor_id) ->where('bill_approval.vendor_approval', '0') ->where('bill_approval.is_paynow_feature', '!=', '3'); $query = $query->flatten();

Snapey's avatar

You need to query the database, then flatten the results. You are trying to use flatten on the query builder.

$query = self::select("bill_approval.*", \DB::raw("CONCAT('".env('AWS_PATH')."', bill_approval.bill_image) as bill_image"))
    ->with(['user:user_id,sso_username', 'category'])
    ->where('bill_approval.vendor_id', $vendor_id)
    ->where('bill_approval.vendor_approval', '0')
    ->where('bill_approval.is_paynow_feature', '!=', '3');

 $query = $query->get()->flatten(1);   // or however many levels you need

and DONT use .env properties directly. Get them from config.

random@94's avatar

i tried but till response is like this.

[ { "col-1": val1 "cal-2": val2, "key1": { "col-1": val1 "cal-2": val2, }, "key2": { "col-1": val,1 "cal-2": val2, }, }, ]

RamjithAp's avatar

Have you tired this?

$query = $query->get()->flatten(2);  // depth parameter

change the depth parameter based on your preferrences. In your case you are trying to flatten child array so 2.

Snapey's avatar

How do you expect to represent nested data sets?

gileneusz's avatar

@Snapey There is a bug with flatten(1), it's getting values from 2 level deep as default, instead of one level.

where to report the bug?

Please or to participate in this conversation.