Laravel API Resource: Loading relationship the right way.

Sam Ngu
4 min readMar 31, 2020

Watch this on YouTube:

Nest eloquent relationship in Laravel Resource classes without fear. Avoiding infinite nested relationship loop in Laravel Resource.

Photo by Karen Ciocca on Unsplash

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.

Entity Relationship Diagram for our app.

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…

--

--