Skip to content

Instantly share code, notes, and snippets.

@uchm4n
Last active February 19, 2020 06:01
Show Gist options
  • Save uchm4n/088def0de23f01f80386edc6a234720c to your computer and use it in GitHub Desktop.
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
<?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