首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从资源模板Laravel 7和8中排除字段

从资源模板Laravel 7和8中排除字段
EN

Stack Overflow用户
提问于 2021-09-08 13:47:27
回答 1查看 66关注 0票数 0

我遇到了一个从控制器CompanyController.php中的资源集合中筛选字段的解决方案

例如,下面的代码返回除company_logo之外的所有值

代码语言:javascript
复制
CompanyResource::collection($companies)->hide(['company_logo']);

CompanyResource.php

代码语言:javascript
复制
<?php

namespace App\Http\Resources;

use Illuminate\Http\Resources\Json\JsonResource;


class CompanyResource extends JsonResource
{
    /**
     * Transform the resource into an array.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return array
     */

    protected $withoutFields = [];

    public static function collection($resource)
    {
        return tap(new CompanyResourceCollection($resource), function ($collection) {
            $collection->collects = __CLASS__;
        });
    }

    // Set the keys that are supposed to be filtered out
    public function hide(array $fields)
    {
        $this->withoutFields = $fields;
        return $this;
    }

    // Remove the filtered keys.
    protected function filterFields($array)
    {
        return collect($array)->forget($this->withoutFields)->toArray();
    }

    public function toArray($request)
    {
        return $this->filterFields([
            'id' => $this->id,
            'name' => $this->name,
            'email' => $this->email,
            'telephone' => $this->telephone,
            'company_logo' => $this->company_logo,
            'social_links' => $this->social_links,
            
        ]);
    }

}

现在,在我的UserResource中,我仍然希望指定不希望从同一个CompanyResource返回的字段,但它在UserResource中不再是一个集合

UserResource.php

代码语言:javascript
复制
public function toArray($request)
    {
        return [
            'id' => $this->id,
            'email' => $this->email,
            'status' => $this->status,
            'timezone' => $this->timezone,
            'last_name' => $this->last_name,
            'first_name' => $this->first_name,
            'tags' => TagResource::collection($this->whenLoaded('tags')),
            'company' => new CompanyResource($this->whenLoaded('company')),
            
        ];
    }

所以我的想法是能够在'company' => new CompanyResource($this->whenLoaded('company')),上指定排除的字段,这些字段已经在这里停留了一段时间。

EN

回答 1

Stack Overflow用户

发布于 2021-09-09 18:00:30

经过研究,我为我的问题找到了一个可行的解决方案

代码语言:javascript
复制
'company' => CompanyResource::make($this->whenLoaded('company'))->hide(['company_logo']),

而不是我不能灵活使用的以下代码:

代码语言:javascript
复制
'company' => new CompanyResource($this->whenLoaded('company')),
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/69104301

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档