mardi 23 octobre 2018

How to avoid infinite loop when nesting api resources in Laravel?

I have two models: Company and Representative. Representative belongsTo Company, Company hasMany Representative.

Also I have two corresponding resources. Company resource:

public function toArray($request)
    {
        return [
            'id'          => $this->id,
            'title'       => $this->title,   
            'representatives' => RepresentativeResource::collection($this->representatives)
        ];
    } 

And representative resource:

 public function toArray($request)
    {
        return [
            'id' => $this->id,
            'company' => $this->company ? new CompanyResource($this->company) : null
        ];
    }

What I want to accomplish is when I get companies I want to get theirs representatives. When I get representative I want to get information about company.

What happens is infinite loop: their include each other infinitely. So, how could it be fixed?



via Chebli Mohamed

Aucun commentaire:

Enregistrer un commentaire