Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

kevariable's avatar

Prevent to loaded One to One relationship on "Laravel API Resource"

Hello guys,

I have tried on docs laravel it's called "whenLoaded" on Laravel API Resource, the problem here is whenLoaded is work on Many relationship meanwhile one relationship must be called, so how can i prevent one to one is loaded on API Resource, considere this bellow code

Travel has one to Schedule

and Schedule one to Travel

and my resource like this

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class TravelResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'schedule' => new TravelScheduleResource($this->schedule),
        ];
    }
}

<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;

class TravelScheduleResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */
    public function toArray($request)
    {
        return [
            'travel' => new TravelResource($this->travel),
        ];
    }
}

and my controller returned

return new ScheduleResource($resource);

and the result get an error

Maximum stack depth exceeded

Thanks in advance for reading my problem :)

0 likes
3 replies
Snapey's avatar

do you have $with in your models?

2 likes
kevariable's avatar

Thanks to reply sir, i has update my controller returned so, $with work with one to many relation or many to many, if belongsTo it will load automaticly without eager loading,

in my case on controller returned ScheduleResource which belongsTo Travel model

Snapey's avatar

I don't know if you understood my question

Clearly you have a recursive loop which is usually caused by two models both automatically eager loading the other by use of $with statements in each model

Please or to participate in this conversation.