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

manojo123's avatar

Explode Query Builder results

Hello Community

I have this query

$locales = Local::select("tbl_locales.cc_id", "tbl_locales.nombre")
            ->selectRaw("GROUP_CONCAT(proveedor_id) as unit_ids")
            ->join('tbl_local_proveedor_id', 'tbl_locales.id', '=', 'tbl_local_proveedor_id.local_id')
            ->where("tbl_locales.estado",1)
            ->where("tbl_locales.red_id",1)
            ->where("tbl_local_proveedor_id.estado",1)
            ->whereNotNull("tbl_local_proveedor_id.proveedor_id")
            ->whereNotNull("tbl_locales.cc_id")
            ->groupBy("tbl_locales.id")->get();

Id like to explode the result of

selectRaw("GROUP_CONCAT(proveedor_id) as unit_ids")

There is some black magic in Laravel that helps me to do this or I will to iterate all locales and explode the values one by one?

Thanks in advance

0 likes
2 replies
manojo123's avatar
manojo123
OP
Best Answer
Level 14

I achieved this by using the function each() in query builder

->groupBy("tbl_locales.id")->get()->each(function($query){
                $query->unit_ids = explode(",", $query->unit_ids);
            });

Now im only considering if there is a shortened way for this but I think this is the best refactor posible.

1 like
realrandyallen's avatar

@MANOJOW - Not sure if there's going to be a better way to do it unless you use Eloquent to setup proper relationships between the two tables so you can do something like:

$local->units

Then you wouldn't have to worry about pulling a string of unit_ids then exploding them into an array. Either way though, just for clarification, you aren't working with the Query builder here anymore since you get(), at that point you're working with a collection so technically this would be the same thing:

->groupBy("tbl_locales.id")->get()->each(function($local){
    $local->unit_ids = explode(",", $local->unit_ids);
});

Please or to participate in this conversation.