Hello,
I have the above error when recursively looping through some eloquent models and their child models in order to set other relationships using setRelation(). On other posts elsewhere I have seen that apparently using laravel Collections in conjunction with recursive functions can cause this error which may be related to memory usage limits. The problem is there doesn't see,m to be a definitive cause of this error. It seems it is a generic error and there seems to be as many explanations as there are posts. The error only occurs on our staging server and not locally. I don't believe it is necessarily a 'fault' with the code more a memory optimisation issue?? This may sound a bit vague but I am clean out of ideas and it seems to be an issue which is not unheard of when working with laravel collections :
Client code:
$organisationProjects = $request->user()->organisation->projects()->get();
$userProjects = $this->userProjects($request->user(), $organisationProjects);
Class functions:
public function userProjects(User $user, $rootProjects)
{
/*
* Start by looking through the entire tree for the root projects to show...
*/
$baseProjects = collect([]);
foreach ($rootProjects as $rootProject) {
$baseProjects = $baseProjects->merge($this->recurse($user, $rootProject));
}
return $baseProjects;
}
public function recurse(User $user, Project $project)
{
$list = collect([]);
if ($user->can('viewProject', $project)) {
$project->setRelation('childProjects', $project->activeChildProjects->map(function (Project $childProject) use ($user): ?Collection {
if ($user->can('viewProject', $childProject)) {
return $this->recurse($user, $childProject);
}
return null;
})->filter()->flatten(1));
$list = $list->push($project);
} else {
foreach ($project->activeChildProjects as $childProject) {
$list = $list->merge($this->recurse($user, $childProject));
}
}
return $list;
}
Thanks