Home > OS >  Laravel 9, split collection by column value
Laravel 9, split collection by column value

Time:11-17

I have a table with types, and second table "cleanings" with a related type_id column.

I get a collection of all cleanings:

$cleanings= Cleaning::with(['propierty'])->get();

And now, I need to split this collection in many collections(or arrays), one for every type_id.

Is there any trick to do it? I can't find any method in collections page for that.

CodePudding user response:

$array = [];

foreach($cleanings as $cleaning) {
    $array[$cleaning->type_id][] = $cleaning;
}

This'll give you an array of arrays, keyed by type_id.

  • Related