Repository navigation
How to include pivot relationship data within the JSON:API resource toRelationships method? #59919
Answered
by
nirav-gajera
SantosVilanculos
asked this question in
Q&A
|
When implementing the toRelationships method in a Laravel JSON:API resource, what is the standard way to include a many-to-many relationship that requires access to pivot table attributes or custom accessors? I am looking for the syntax to ensure that when withPivot or a custom Pivot model is used, the data is correctly mapped into the relationship's data. |
Answered by
nirav-gajera
May 14, 2026
Replies: 1 comment 2 replies
|
Include pivot data in your resource attributes, not in the relationship definition. Model Setuppublic function roles()
{
return $this->belongsToMany(Role::class)->withPivot('assigned_at');
}Resource Implementationclass RoleResource extends JsonApiResource
{
public function toAttributes(): array
{
return [
'name' => $this->resource->name,
'assignedAt' => $this->when(
isset($this->resource->pivot),
$this->resource->pivot?->assigned_at
),
];
}
public function toRelationships(): array
{
return [];
}
}User Resourceclass UserResource extends JsonApiResource
{
public function toRelationships(): array
{
return [
'roles' => ToMany::make($this->roles),
];
}
}The The standard approach is to:
|
2 replies
Answer selected by
SantosVilanculos
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Include pivot data in your resource attributes, not in the relationship definition.
Model Setup
Resource Implementation
User Resource