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

dmag's avatar
Level 6

Array instead of model to api resource with relation

I use the following ExamResource in two places.

class ExamResource extends JsonResource
{
    public function toArray($request): array
    {
        return [
            'id' => $this->resource['id'],
            'date' => $this->resource['date'],
            'results' => ResultResource::collection($this->whenLoaded('results')),
        ];
    }
}

In one place I pass the Exam model to it:

$exams = Exam::all();

return ExamResource::collection($exams);

In another place I pass an array.

$exams = [
    ['id' => 12345, 'date' => '2015-01-28'],
];

return ExamResource::collection($exams);

I also try to include relation when it's loaded, but when I pass the array I get this error:

Call to a member function relationLoaded() on array

How do I make it work?

0 likes
1 reply
LaryAI's avatar
Level 58

The error message "Call to a member function relationLoaded() on array" occurs because the whenLoaded method is called on an array instead of a model. To fix this, you can create a new instance of the model and pass the array to it. Here's an example:

$exams = [
    ['id' => 12345, 'date' => '2015-01-28'],
];

$examModels = collect($exams)->map(function ($exam) {
    return new Exam($exam);
});

return ExamResource::collection($examModels);

In this example, we create a new collection of Exam models from the array using the map method. Then we pass this collection to the ExamResource instead of the original array. This way, the whenLoaded method will work as expected.

2 likes

Please or to participate in this conversation.