Last active
February 19, 2020 06:01
-
-
Save uchm4n/088def0de23f01f80386edc6a234720c to your computer and use it in GitHub Desktop.
Simplify your nested Laravel collection with pluck function or using crossJoin and eachSpread
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$customers = collect([]); // some nested Laravel collection | |
// Instead of manually creating this monstrous nested loop... | |
$customers->each(function ($customer) { | |
$customer->orders->each(function ($order) { | |
$order->payments->each(function ($payment) { | |
//doWork($payment); | |
}); | |
}); | |
}); | |
// we can use pluck with dots and stars to fetch deeply nested layers | |
$customers->pluck("orders.*.payments")->flatten()->each(function ($payment){ | |
//doWork($payment); | |
}); | |
//------- ------- ------- ------- ------- ------- // | |
// or this nested loop | |
$customers->each(function ($customer) use ($teams, $dates) { | |
$teams->each(function ($team) use ($customer, $dates) { | |
$dates->each(function ($date) use ($customer, $team) { | |
doWork($customer, $team, $date); | |
}); | |
}); | |
}); | |
// to this | |
$customers->crossJoin($teams, $dates)->eachSpread(function ($customer, $team, $date) { | |
doWork($customer, $team, $date); | |
}); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment