Home > other >  Maximum stack depth exceeded in Laravel 8
Maximum stack depth exceeded in Laravel 8

Time:09-30

i have a ressource collection :

class OverviewResource extends JsonResource
{
    
    public function toArray($request): array
    {
        return [
            'first_name' => $this->first_name,
            'last_name' => $this->last_name,
            'email' => $this->email, 
            'phone' => $this->phone,
            'friends' => OverviewResource::collection(User::getFriends()),
        ];
    }
}

i have an error in this line

'friends' => OverviewResource::collection(User::getFriends()),

when calling this function from User model

    public static function getFriends(){
         return User::where
            //query code here
        })->get();
    }

i got this error

Maximum stack depth exceeded

CodePudding user response:

If a user has n friends then:

OverviewResource::collection(User::getFriends())

is going to create n new resources.

Each of those resources will call:

OverviewResource::collection(User::getFriends())

and create n new resources.

Each of those new resources then calls it again, and then the new ones again, ... Until you reach the maximum stack allowed.

You're going to have to rethink how you implement your recursion so that it terminates.

  • Related