Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/laravel/11.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
通过Laravel使用具有不同细节级别的相同资源_Laravel - Fatal编程技术网

通过Laravel使用具有不同细节级别的相同资源

通过Laravel使用具有不同细节级别的相同资源,laravel,Laravel,如何在Laravel中使用具有不同属性的相同资源 假设我有一个User和一个Post模型。在PostResource中,我还使用了UserResource: public function toArray($request) { return [ 'id' => $this->id, 'body' => $this->body, 'created_at' => $this->created_at,

如何在Laravel中使用具有不同属性的相同
资源

假设我有一个
User
和一个
Post
模型。在
PostResource
中,我还使用了
UserResource

public function toArray($request)
{
    return [
        'id' => $this->id,
        'body' => $this->body,
        'created_at' => $this->created_at,
        'image' => $this->image_url,
        'intro' => $this->intro,
        'slug' => $this->slug,
        'title' => $this->title,
        'user' => new UserResource($this->user),
    ];
}
在这里,UserResource只需要返回几个属性,例如:

return [
        'country' => $this->country,
        'image' => $this->image_url,
        'username' => $this->username,
    ];
但是当在另一个场景中使用
UserResource
时,例如配置文件,我需要更多关于用户的信息。我可以创建一个
UserProfileResource
,但这对我来说并不合适

那么,这方面的常见做法/最佳解决方案是什么

我可以创建一个UserProfileResource,但这对我来说并不合适


是的,您“应该”为需要/想要的不同响应创建不同的资源。这些资源类是“便宜”的,所以不要害怕制作您所需要的资源类。

为什么要在不同的场景中使用相同的资源类?使用两个资源类是个好主意。@milo这不是资源的概念。在购物系统的上下文中,发送者是与用户资源完全不同的资源,即使它们是相同的实体。