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

Hala's avatar
Level 3

try to load pivot table using Api resource

public function toArray($request) { return [

              'languages' => $this->whenPivotLoaded('planner_languages', function () {
            return $this->language;
        }),
      
    ];
}

i'm trying languages but api rescoures return with out it even that the relation is correct and i can see the relation if i remove condition

0 likes
3 replies
frankincredible's avatar
Level 14

Just making some clarification assumptions here:

You have a Planner Model that has a languages() relationship.

In your Resource, you want to include the pivot data (the data from the joining planner_languages table).

In this case, the field from the pivot table you want to include is called language ?

In that case, your code is very close. You just need to add pivot-> before language:

              'languages' => $this->whenPivotLoaded('planner_languages', function () {
            return $this->pivot->language;
        }),
      
    ];
}

If, alternatively, the field language is on the languages table, not the planner_languages pivot table, then you may be looking for whenLoaded:

'languages' => LanguageResource::collection($this->whenLoaded('languages')),

One last thing:

Make sure the pivot table is actually called planner_languages as you have it in your code. The convention for Laravel pivot tables is a) both words are singular and b) the words are in alphabetical order. Example: language_planner

1 like
Hala's avatar
Level 3

yes i was check the pivot and the name is correct and i use return $this->pivot->language; and nope nth appear

Hala's avatar
Level 3

But thank you very much i did LanguageResource and it's work

Please or to participate in this conversation.