You can determine the type of the morph using instanceof. Something like this:
public function toArray($request)
{
return [
// ...
'resource' => $this->when($this->relationLoaded('resource'), function () {
if ($this->resource->resource instanceof App\Post) {
return new PostResource($this->resource->resource);
}
if ($this->resource->resource instanceof App\Picture) {
return new PictureResource($this->resource->resource);
}
}),
];
}
I haven't tested this, and I agree it looks a bit awkward with the $this->resource->resource, but I think it's the only way it would work. Normally 'this' (the resource) magically catches property access and forwards it to the underlying resource (the model). But since $resource is used for the resource object, which happens to also be the name of your relationship, you need to be explicit.