What isn't working? Getting an error or an unexpected result?
API Resource with Polymorphic Relationships
Hi,
I have a situation where my User and Group models can share a one-to-one polymorphic relationship with a Calendar model. I need my Calendar API Resource to include either the User or Group it's associated with. How do I do this?
After reading up this post, this is my set up:
<?php
// The models
class Calendar extends Model
{
/
public function calendarable()
{
return $this->morphTo();
}
}
class User extends Model
{
public function calendar()
{
return $this->morphOne('App\Calendar', 'calendarable');
}
}
class Group extends Model
{
public function calendar()
{
return $this->morphOne('App\Calendar', 'calendarable');
}
}
<?php
// Calendar API Resource
class CalendarResource extends JsonResource
{
public function toArray($request)
{
return [
'id' => $this->id,
'calendarable_id' => $this->calendarable_id,
'owner' => $this->when($this->relationLoaded('calendarable'), function () {
switch (true) {
case $this->calendarable instanceof \App\User:
return new UserResource($this->calendarable);
case $this->calendarable instanceof \App\Group:
return new GroupResource($this->calendarable);
}
})
];
}
}
The above loads the appropriate resource class, but it's giving me a Maximum stack depth exceeded error.
More background: The Calendar and User model used to share a one-to-one relationship and in the Calendar API resource, 'owner' => new UserResource($this->whenLoaded('user')) would properly load the resource class. The Groups model is new so I converted the existing Calendar and User relation to the polymorphic relationship described above.
Any help will be greatly appreciated!
Well a bit of debugging is a good place to start.
Comment out the owner section and just do this.
'owner' => $this->calenderable,
Is the error gone?
Please or to participate in this conversation.