You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When using Laravel, one has the option of using a custom resource class that extends JsonResource to transform resources in http requests.
If you try to override the other methods in the JsonResource class however, there's a 99% chance no other method you override will be called except toArray, the reason is because when the Router toResponse is called, it invokes a second toResponse on the AnonymousResourceCollection and ends up in a chain of original class calls where the actual collector class is never used albeit overriding JsonResource.
One possible approach is to invoke the actual resource collector from ResourceCollection
For example instead of:
public function toResponse($request)
{
if ($this->resource instanceof AbstractPaginator || $this->resource instanceof AbstractCursorPaginator) {
return $this->preparePaginatedResponse($request);
}
return parent::toResponse($request);
}
We could have:
$collector = new $this->collects($this->resource);
return $collector->toResponse($request);
This way, users can benefit fully from http resources.
reacted with thumbs up emoji reacted with thumbs down emoji reacted with laugh emoji reacted with hooray emoji reacted with confused emoji reacted with heart emoji reacted with rocket emoji reacted with eyes emoji
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
When using Laravel, one has the option of using a custom resource class that extends JsonResource to transform resources in http requests.
If you try to override the other methods in the JsonResource class however, there's a 99% chance no other method you override will be called except toArray, the reason is because when the
Router toResponse
is called, it invokes a secondtoResponse
on theAnonymousResourceCollection
and ends up in a chain of original class calls where the actual collector class is never used albeit overriding JsonResource.One possible approach is to invoke the actual resource collector from
ResourceCollection
For example instead of:
We could have:
This way, users can benefit fully from http resources.
Beta Was this translation helpful? Give feedback.
All reactions