簡體   English   中英

使用 Laravel API 資源時如何刪除集合中的某些值

[英]How to remove some values in collection when using Laravel API Resource

我在一個博客項目中。 我的 Post 模型有這個 API 資源

return [
    'id' => $this->id,
    'title' => $this->title,
    'body' => $this->body,
    'date' => $this->date
];

但我不想在我收集帖子時得到'body' => $this->body ,因為我只在我想顯示帖子時使用它,而不是為了列出它們

我怎樣才能做到這一點 ? 我應該使用資源集合嗎?

更新: makeHidden應該可以工作,但它不會因為我們有Illuminate\\Support\\Collection而不是Illuminate\\Database\\Eloquent\\Collection ,我如何進行強制轉換或使 API 資源的集合方法返回一個Illuminate\\Database\\Eloquent\\Collection實例 ?

有一種方法可以有條件地向資源添加屬性,如下所示

return [
    'attribute' => $this->when(Auth::user()->isAdmin(), 'attribute-value'),
];

我希望這能幫到您

我假設你有一個PostResource ,如果你沒有,你可以生成一個:

php artisan make:resource PostResource

覆蓋PostResource和 filter 字段上的收集方法:

class PostResource extends Resource
{
    protected $withoutFields = [];

    public static function collection($resource)
    {
        return tap(new PostResourceCollection($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,
            'title' => $this->title,
            'body' => $this->body,
            'date' => $this->date
        ]);
    }
}

您需要創建一個PostResourceCollection

php artisan make:resource --collection PostResourceCollection 

這里正在使用隱藏字段處理集合

class PostResourceCollection extends ResourceCollection
{
    protected $withoutFields = [];

    // Transform the resource collection into an array.
    public function toArray($request)
    {
        return $this->processCollection($request);
    }

    public function hide(array $fields)
    {
        $this->withoutFields = $fields;
        return $this;
    }
    // Send fields to hide to UsersResource while processing the collection.
    protected function processCollection($request)
    {
        return $this->collection->map(function (PostResource $resource) use ($request) {
            return $resource->hide($this->withoutFields)->toArray($request);
        })->all();
    }
}

現在在PostController您可以使用要隱藏的字段調用hide方法:

public function index()
{
    $posts = Post::all();
    return PostResource::collection($posts)->hide(['body']);
}

你應該得到一個沒有 body 字段的 Posts 集合。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM