Nest eloquent relationship in Laravel Resource classes without fear. Avoiding infinite nested relationship loop in Laravel Resource.
Laravel Resource Classes are great! They allow us to control what data in a model to return in an API response.
Let’s say we are building an API for our app. We have the following relationships for our MySQL database.
The Issue
Infinite loop in Resource when parent and children call each other
Now let’s write our resource classes for our company model. We want to include users when we call the company API. We usually do something like this in the Company Resource class:
class CompanyResource extends JsonResource
{
/**
* Transform the resource into an…