API Resource Support Multiple Return Data Formats #54738
Unanswered
denmasyarikin
asked this question in
Ideas
Replies: 2 comments
-
We had a similar need but in regards to json or streamed download. |
Beta Was this translation helpful? Give feedback.
0 replies
-
You can simplify your need by using current implementation: public function toArray($request): array
{
$routeAlias = $request->route()->getName();
if ($routeAlias === 'list') {
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'status' => $this->status,
'created_at' => $this->created_at
];
}
if ($routeAlias === 'embed') {
return [
'id' => $this->id,
'title' => $this->title
];
}
return [
'id' => $this->id,
'title' => $this->title,
'description' => $this->description,
'content' => $this->content,
'author' => new AuthorResource($this->whenLoaded('author')),
'status' => $this->status,
'created_at' => $this->created_at
];
} And you would need to put an alias on each route when you define it. Alternative is to send that flag in the request if you want to not define 3 routes for the same resource. |
Beta Was this translation helpful? Give feedback.
0 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Currently, a single Laravel API Resource can only return one format of data. However, in real-world applications, we often need multiple data sets for the same resource to optimize response sizes for different use cases.
For example, for an Article resource, we might need:
Detail
: Full data with all relationships.List
: Summary data for listings.Embedded
: Minimal data for embedding in other resources.To achieve this, we currently need to create multiple resource classes, such as
ListArticleResource
,DetailArticleResource
, andEmbedArticleResource
, which increases maintenance complexity.Detail
we need all data with all relationships:List
we need:Embeded
we just need:Proposed Solution
In Api Resouce support multiple view
so we can use
in resource as embeded
Beta Was this translation helpful? Give feedback.
All reactions