I have a nested array of objects inside an array of objects.
Pages
hasMany sections
I am trying to unset the nested sections and reset their array keys but to no avail.
foreach ($pages as $pageKey => &$page) {
foreach ($page->sections as $sectionKey => $section) {
// Remove sections with no questions
if ($section->questions->count() < 1) {
$page->sections->forget($sectionKey);
}
}
$page->sections = $page->sections->values()->all();
}
However, the section keys are not being reset.
What (I assume) you are trying to do is get all the Page
s with Section
s that has at least Comment
s. In order to accomplish this you could do this in one query:
$pages = Pages::with(['sections' => function ($query) {
$query->has('comments');
}])
->get();
With this, you are eager loading the Section
s related the every Page
but just the ones that has at least one Comment linked to them.
You can check the documentation related to this topics: